mapbox.services package

Submodules

mapbox.services.analytics module

class mapbox.services.analytics.Analytics(access_token=None, host=None, cache=None)

Bases: mapbox.services.base.Service

Access to Analytics API V1

Attributes:
api_name : str

The API’s name.

api_version : str

The API’s version number.

valid_resource_types : list

The possible values for the resource being requested.

Methods

analytics(resource_type, username[, id, …]) Returns the request counts per day for a given resource and period.
handle_http_error(response[, …]) Converts service errors to Python exceptions
analytics(resource_type, username, id=None, start=None, end=None)

Returns the request counts per day for a given resource and period.

Parameters:
resource_type : str

The resource being requested.

Possible values are “tokens”, “styles”, “tilesets”, and “accounts”.

username : str

The username for the account that owns the resource.

id : str, optional

The id for the resource.

If resource_type is “tokens”, then id is the complete token. If resource_type is “styles”, then id is the style id. If resource_type is “tilesets”, then id is a map id. If resource_type is “accounts”, then id is not required.

start, end : str, optional

ISO-formatted start and end dates.

If provided, the start date must be earlier than the end date, and the maximum length of time between the start and end dates is one year.

If not provided, the length of time between the start and end dates defaults to 90 days.

Returns:
requests.Response
api_name = 'analytics'
api_version = 'v1'
valid_resource_types = ['tokens', 'styles', 'accounts', 'tilesets']

mapbox.services.base module

Base Service class

class mapbox.services.base.Service(access_token=None, host=None, cache=None)

Bases: object

Service base class

Attributes:
default_host : str

Default service hostname: api.mapbox.com.

api_name : str

Mapbox API name.

api_version : str

API version string such as “v1” or “v5”.

baseuri

The service’s base URI

username

The username in the service’s access token

Methods

handle_http_errors(response, custom_messages=None, raise_for_status=False) Converts service errors to Python exceptions.
api_name = 'hors service'
api_version = 'v0'
baseuri

The service’s base URI

Returns:
str
default_host = 'api.mapbox.com'
handle_http_error(response, custom_messages=None, raise_for_status=False)

Converts service errors to Python exceptions

Parameters:
response : requests.Response

A service response.

custom_messages : dict, optional

A mapping of custom exception messages to HTTP status codes.

raise_for_status : bool, optional

If True, the requests library provides Python exceptions.

Returns:
None
username

The username in the service’s access token

Returns:
str
mapbox.services.base.Session(access_token=None, env=None)

Create an HTTP session.

Parameters:
access_token : str

Mapbox access token string (optional).

env : dict, optional

A dict that subsitutes for os.environ.

Returns:
requests.Session

mapbox.services.datasets module

class mapbox.services.datasets.Datasets(access_token=None, host=None, cache=None)

Bases: mapbox.services.base.Service

Access to the Datasets API V1

Attributes:
api_name : str

The API’s name.

api_version : str

The API’s version number.

Methods

create([name, description]) Creates a new, empty dataset.
delete_dataset(dataset) Deletes a single dataset, including all of the features that it contains.
delete_feature(dataset, fid) Removes a feature from a dataset.
handle_http_error(response[, …]) Converts service errors to Python exceptions
list() Lists all datasets for a particular account.
list_features(dataset[, reverse, start, limit]) Lists features in a dataset.
read_dataset(dataset) Retrieves (reads) a single dataset.
read_feature(dataset, fid) Retrieves (reads) a feature in a dataset.
update_dataset(dataset[, name, description]) Updates a single dataset.
update_feature(dataset, fid, feature) Inserts or updates a feature in a dataset.
api_name = 'datasets'
api_version = 'v1'
create(name=None, description=None)

Creates a new, empty dataset.

Parameters:
name : str, optional

The name of the dataset.

description : str, optional

The description of the dataset.

Returns:
request.Response

The response contains the properties of a new dataset as a JSON object.

delete_dataset(dataset)

Deletes a single dataset, including all of the features that it contains.

Parameters:
dataset : str

The dataset id.

Returns:
HTTP status code.
delete_feature(dataset, fid)

Removes a feature from a dataset.

Parameters:
dataset : str

The dataset id.

fid : str

The feature id.

Returns:
HTTP status code.
list()

Lists all datasets for a particular account.

Returns:
request.Response

The response contains a list of JSON objects describing datasets.

list_features(dataset, reverse=False, start=None, limit=None)

Lists features in a dataset.

Parameters:
dataset : str

The dataset id.

reverse : str, optional

List features in reverse order.

Possible value is “true”.

start : str, optional

The id of the feature after which to start the list (pagination).

limit : str, optional

The maximum number of features to list (pagination).

Returns:
request.Response

The response contains the features of a dataset as a GeoJSON FeatureCollection.

read_dataset(dataset)

Retrieves (reads) a single dataset.

Parameters:
dataset : str

The dataset id.

Returns:
request.Response

The response contains the properties of the retrieved dataset as a JSON object.

read_feature(dataset, fid)

Retrieves (reads) a feature in a dataset.

Parameters:
dataset : str

The dataset id.

fid : str

The feature id.

Returns:
request.Response

The response contains a GeoJSON representation of the feature.

update_dataset(dataset, name=None, description=None)

Updates a single dataset.

Parameters:
dataset : str

The dataset id.

name : str, optional

The name of the dataset.

description : str, optional

The description of the dataset.

Returns:
request.Response

The response contains the properties of the updated dataset as a JSON object.

update_feature(dataset, fid, feature)

Inserts or updates a feature in a dataset.

Parameters:
dataset : str

The dataset id.

fid : str

The feature id.

If the dataset has no feature with the given feature id, then a new feature will be created.

feature : dict

The GeoJSON feature object.

This should be one individual GeoJSON feature and not a GeoJSON FeatureCollection.

Returns:
request.Response

The response contains a GeoJSON representation of the new or updated feature.

mapbox.services.directions module

class mapbox.services.directions.Directions(access_token=None, host=None, cache=None)

Bases: mapbox.services.base.Service

Access to the Directions v5 API.

Attributes:
baseuri

The service’s base URI

username

The username in the service’s access token

Methods

directions(features[, profile, …]) Request directions for waypoints encoded as GeoJSON features.
handle_http_error(response[, …]) Converts service errors to Python exceptions
api_name = 'directions'
api_version = 'v5'
baseuri

The service’s base URI

Returns:
str
directions(features, profile='mapbox/driving', alternatives=None, geometries=None, overview=None, steps=None, continue_straight=None, waypoint_snapping=None, annotations=None, language=None, **kwargs)

Request directions for waypoints encoded as GeoJSON features.

Parameters:
features : iterable

An collection of GeoJSON features

profile : str

Name of a Mapbox profile such as ‘mapbox.driving’

alternatives : bool

Whether to try to return alternative routes, default: False

geometries : string

Type of geometry returned (geojson, polyline, polyline6)

overview : string or False

Type of returned overview geometry: ‘full’, ‘simplified’, or False

steps : bool

Whether to return steps and turn-by-turn instructions, default: False

continue_straight : bool

Direction of travel when departing intermediate waypoints

radiuses : iterable of numbers or ‘unlimited’

Must be same length as features

waypoint_snapping : list

Controls snapping of waypoints

The list is zipped with the features collection and must have the same length. Elements of the list must be one of:

  • A number (interpretted as a snapping radius)
  • The string ‘unlimited’ (unlimited snapping radius)
  • A 3-element tuple consisting of (radius, angle, range)
  • None (no snapping parameters specified for that waypoint)
annotations : str

Whether or not to return additional metadata along the route

Possible values are: ‘duration’, ‘distance’, ‘speed’, and ‘congestion’. Several annotations can be used by joining them with ‘,’.

language : str

Language of returned turn-by-turn text instructions, default: ‘en’

Returns:
requests.Response

The response object has a geojson() method for access to the route(s) as a GeoJSON-like FeatureCollection dictionary.

valid_annotations = ['duration', 'distance', 'speed']
valid_geom_encoding = ['geojson', 'polyline', 'polyline6']
valid_geom_overview = ['full', 'simplified', False]
valid_profiles = ['mapbox/driving', 'mapbox/driving-traffic', 'mapbox/walking', 'mapbox/cycling']

mapbox.services.geocoding module

class mapbox.services.geocoding.Geocoder(name='mapbox.places', access_token=None, cache=None, host=None)

Bases: mapbox.services.base.Service

Access to the Geocoding API V5

Attributes:
baseuri

The service’s base URI

country_codes

A list of valid country codes

place_types

A mapping of place type names to descriptions

username

The username in the service’s access token

Methods

forward(address[, types, lon, lat, country, …]) Returns a Requests response object that contains a GeoJSON collection of places matching the given address.
handle_http_error(response[, …]) Converts service errors to Python exceptions
reverse(lon, lat[, types, limit]) Returns a Requests response object that contains a GeoJSON collection of places near the given longitude and latitude.
api_name = 'geocoding'
api_version = 'v5'
country_codes

A list of valid country codes

forward(address, types=None, lon=None, lat=None, country=None, bbox=None, limit=None, languages=None)

Returns a Requests response object that contains a GeoJSON collection of places matching the given address.

response.geojson() returns the geocoding result as GeoJSON. response.status_code returns the HTTP API status code.

Place results may be constrained to those of one or more types or be biased toward a given longitude and latitude.

See: https://www.mapbox.com/api-documentation/#geocoding.

place_types

A mapping of place type names to descriptions

precision = {'proximity': 3, 'reverse': 5}
reverse(lon, lat, types=None, limit=None)

Returns a Requests response object that contains a GeoJSON collection of places near the given longitude and latitude.

response.geojson() returns the geocoding result as GeoJSON. response.status_code returns the HTTP API status code.

See: https://www.mapbox.com/api-documentation/#retrieve-places-near-a-location.

mapbox.services.mapmatching module

class mapbox.services.mapmatching.MapMatcher(access_token=None, host=None, cache=None)

Bases: mapbox.services.base.Service

Access to the Map Matching API V4

Attributes:
baseuri

The service’s base URI

username

The username in the service’s access token

Methods

handle_http_error(response[, …]) Converts service errors to Python exceptions
match(feature[, gps_precision, profile]) Match features to OpenStreetMap data.
api_name = 'matching'
api_version = 'v4'
match(feature, gps_precision=None, profile='mapbox.driving')

Match features to OpenStreetMap data.

valid_profiles = ['mapbox.driving', 'mapbox.cycling', 'mapbox.walking']

mapbox.services.matrix module

Matrix API V1

class mapbox.services.matrix.DirectionsMatrix(access_token=None, host=None, cache=None)

Bases: mapbox.services.base.Service

Access to the Matrix API V1

Attributes:
baseuri

The service’s base URI

username

The username in the service’s access token

Methods

handle_http_error(response[, …]) Converts service errors to Python exceptions
matrix(coordinates[, profile, sources, …]) Request a directions matrix for trips between coordinates
api_name = 'directions-matrix'
api_version = 'v1'
baseuri

The service’s base URI

Returns:
str
matrix(coordinates, profile='mapbox/driving', sources=None, destinations=None, annotations=None)

Request a directions matrix for trips between coordinates

In the default case, the matrix returns a symmetric matrix, using all input coordinates as sources and destinations. You may also generate an asymmetric matrix, with only some coordinates as sources or destinations:

Parameters:
coordinates : sequence

A sequence of coordinates, which may be represented as GeoJSON features, GeoJSON geometries, or (longitude, latitude) pairs.

profile : str

The trip travel mode. Valid modes are listed in the class’s valid_profiles attribute.

annotations : list

Used to specify the resulting matrices. Possible values are listed in the class’s valid_annotations attribute.

sources : list

Indices of source coordinates to include in the matrix. Default is all coordinates.

destinations : list

Indices of destination coordinates to include in the matrix. Default is all coordinates.

Returns:
requests.Response
Note: the directions matrix itself is obtained by calling the
response’s json() method. The resulting mapping has a code,
the destinations and the sources, and depending of the
annotations specified, it can also contain a durations matrix,
a distances matrix or both of them (by default, only the
durations matrix is provided).
code : str

Status of the response

sources : list

Results of snapping selected coordinates to the nearest addresses.

destinations : list

Results of snapping selected coordinates to the nearest addresses.

durations : list

An array of arrays representing the matrix in row-major order. durations[i][j] gives the travel time from the i-th source to the j-th destination. All values are in seconds. The duration between the same coordinate is always 0. If a duration can not be found, the result is null.

distances : list

An array of arrays representing the matrix in row-major order. distances[i][j] gives the distance from the i-th source to the j-th destination. All values are in meters. The distance between the same coordinate is always 0. If a distance can not be found, the result is null.

valid_annotations = ['duration', 'distance']
valid_profiles = ['mapbox/driving', 'mapbox/cycling', 'mapbox/walking', 'mapbox/driving-traffic']

mapbox.services.static module

class mapbox.services.static.Static(access_token=None, host=None, cache=None)

Bases: mapbox.services.base.Service

Access to the Static Map API V4

Attributes:
api_name
baseuri

The service’s base URI

username

The username in the service’s access token

Methods

handle_http_error(response[, …]) Converts service errors to Python exceptions
image  
api_name = None
api_version = 'v4'
baseuri

The service’s base URI

Returns:
str
image(mapid, lon=None, lat=None, z=None, features=None, width=600, height=600, image_format='png256', sort_keys=False, retina=False)

mapbox.services.static_style module

class mapbox.services.static_style.StaticStyle(access_token=None, host=None, cache=None)

Bases: mapbox.services.base.Service

Access to the Static Map API V1

Attributes:
baseuri

The service’s base URI

username

The username in the service’s access token

Methods

handle_http_error(response[, …]) Converts service errors to Python exceptions
tile(username, style_id, z, x, y[, …]) /styles/v1/{username}/{style_id}/tiles/{tileSize}/{z}/{x}/{y}{@2x}
image  
wmts  
api_name = 'styles'
api_version = 'v1'
image(username, style_id, lon=None, lat=None, zoom=None, features=None, pitch=0, bearing=0, width=600, height=600, retina=None, sort_keys=False, attribution=None, logo=None, before_layer=None, twox=None)
tile(username, style_id, z, x, y, tile_size=512, retina=False)

/styles/v1/{username}/{style_id}/tiles/{tileSize}/{z}/{x}/{y}{@2x}

wmts(username, style_id)
mapbox.services.static_style.validate_bearing(val)
mapbox.services.static_style.validate_image_size(val)
mapbox.services.static_style.validate_lat(val)
mapbox.services.static_style.validate_lon(val)
mapbox.services.static_style.validate_overlay(val)
mapbox.services.static_style.validate_pitch(val)

mapbox.services.tilequery module

The Tilequery class provides access to Mapbox’s Tilequery API.

class mapbox.services.tilequery.Tilequery(access_token=None, host=None, cache=None)

Bases: mapbox.services.base.Service

Access to Tilequery API V4

Attributes:
api_name : str

The API’s name.

api_version : str

The API’s version number.

valid_geometries : list

The possible values for geometry.

base_uri : str

Forms base URI.

Methods

handle_http_error(response[, …]) Converts service errors to Python exceptions
tilequery(map_id[, lon, lat, radius, limit, …]) Returns data about specific features from a vector tileset.
api_name = 'tilequery'
api_version = 'v4'
base_uri

Forms base URI.

tilequery(map_id, lon=None, lat=None, radius=None, limit=None, dedupe=None, geometry=None, layers=None)

Returns data about specific features from a vector tileset.

Parameters:
map_id : str or list

The tileset’s unique identifier in the format username.id.

map_id may be either a str with one value or a list with multiple values.

lon : float

The longitude to query, where -180 is the minimum value and 180 is the maximum value.

lat : float

The latitude to query, where -85.0511 is the minimum value and 85.0511 is the maximum value.

radius : int, optional

The approximate distance in meters to query, where 0 is the minimum value. (There is no maximum value.)

If None, the default value is 0.

limit : int, optional

The number of features to return, where 1 is the minimum value and 50 is the maximum value.

If None, the default value is 5.

dedupe : bool, optional

Whether to remove duplicate results.

If None, the default value is True.

geometry : str, optional

The geometry type to query.

layers : list, optional

The list of layers to query.

If a specified layer does not exist, then the Tilequery API will skip it. If no layers exist, then the API will return an empty GeoJSON FeatureCollection.

Returns:
request.Response

The response object with a GeoJSON FeatureCollection of features at or near the specified longitude and latitude.

valid_geometries = ['linestring', 'point', 'polygon']

mapbox.services.uploads module

Mapbox Uploads API

class mapbox.services.uploads.Uploader(access_token=None, host=None, cache=None)

Bases: mapbox.services.base.Service

Access to the Upload API V1

Example usage:

from mapbox import Uploader

u = Uploader() url = u.stage(open(‘test.tif’, ‘rb’)) job = u.create(url, ‘test1’).json()

assert job in u.list().json()

# … wait unti finished … finished = u.status(job).json()[‘complete’]

u.delete(job) assert job not in u.list().json()

Attributes:
baseuri

The service’s base URI

username

The username in the service’s access token

Methods

create(stage_url, tileset[, name, patch]) Create a tileset
delete(upload[, account, username]) Delete the specified upload
handle_http_error(response[, …]) Converts service errors to Python exceptions
list([account, username]) List of all uploads
stage(fileobj[, creds, callback]) Stages data in a Mapbox-owned S3 bucket
status(upload[, account, username]) Check status of upload
upload(fileobj, tileset[, name, patch, callback]) Upload data and create a Mapbox tileset
api_name = 'uploads'
api_version = 'v1'
create(stage_url, tileset, name=None, patch=False)

Create a tileset

Note: this step is refered to as “upload” in the API docs; This class’s upload() method is a high-level function which acts like the Studio upload form.

Returns a response object where the json() contents are an upload dict. Completion of the tileset may take several seconds or minutes depending on size of the data. The status() method of this class may be used to poll the API endpoint for tileset creation status.

Parameters:
stage_url: str

URL to resource on S3, typically provided in the response of this class’s stage() method.

tileset: str

The id of the tileset set to be created. Username will be prefixed if not present. For example, ‘my-tileset’ becomes ‘{username}.my-tileset’.

name: str

A short name for the tileset that will appear in Mapbox studio.

patch: bool

Optional patch mode which requires a flag on the owner’s account.

Returns:
requests.Response
delete(upload, account=None, username=None)

Delete the specified upload

Parameters:
upload: str

The id of the upload or a dict with key ‘id’.

username : str

Account username, defaults to the service’s username.

account : str, deprecated

Alias for username. Will be removed in version 1.0.

Returns:
requests.Response
list(account=None, username=None)

List of all uploads

Returns a Response object, the json() method of which returns a list of uploads

Parameters:
username : str

Account username, defaults to the service’s username.

account : str, deprecated

Alias for username. Will be removed in version 1.0.

Returns:
requests.Response
stage(fileobj, creds=None, callback=None)

Stages data in a Mapbox-owned S3 bucket

If creds are not provided, temporary credentials will be generated using the Mapbox API.

Parameters:
fileobj: file object or filename

A Python file object opened in binary mode or a filename.

creds: dict

AWS credentials allowing uploads to the destination bucket.

callback: func

A function that takes a number of bytes processed as its sole argument.

Returns:
str

The URL of the staged data

status(upload, account=None, username=None)

Check status of upload

Parameters:
upload: str

The id of the upload or a dict with key ‘id’.

username : str

Account username, defaults to the service’s username.

account : str, deprecated

Alias for username. Will be removed in version 1.0.

Returns:
requests.Response
upload(fileobj, tileset, name=None, patch=False, callback=None)

Upload data and create a Mapbox tileset

Effectively replicates the Studio upload feature. Returns a Response object, the json() of which returns a dict with upload metadata.

Parameters:
fileobj: file object or str

A filename or a Python file object opened in binary mode.

tileset: str

A tileset identifier such as ‘{owner}.my-tileset’.

name: str

A short name for the tileset that will appear in Mapbox studio.

patch: bool

Optional patch mode which requires a flag on the owner’s account.

callback: func

A function that takes a number of bytes processed as its sole argument. May be used with a progress bar.

Returns:
requests.Response

Module contents