mapbox.services package

Submodules

mapbox.services.analytics module

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

Bases: Service

Access to Analytics API V1

Attributes
api_namestr

The API’s name.

api_versionstr

The API’s version number.

valid_resource_typeslist

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_typestr

The resource being requested.

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

usernamestr

The username for the account that owns the resource.

idstr, 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, endstr, 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_hoststr

Default service hostname: api.mapbox.com.

api_namestr

Mapbox API name.

api_versionstr

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'
property 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
responserequests.Response

A service response.

custom_messagesdict, optional

A mapping of custom exception messages to HTTP status codes.

raise_for_statusbool, optional

If True, the requests library provides Python exceptions.

Returns
None
property 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_tokenstr

Mapbox access token string (optional).

envdict, 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: Service

Access to the Datasets API V1

Attributes
api_namestr

The API’s name.

api_versionstr

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
namestr, optional

The name of the dataset.

descriptionstr, 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
datasetstr

The dataset id.

Returns
HTTP status code.
delete_feature(dataset, fid)

Removes a feature from a dataset.

Parameters
datasetstr

The dataset id.

fidstr

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
datasetstr

The dataset id.

reversestr, optional

List features in reverse order.

Possible value is “true”.

startstr, optional

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

limitstr, 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
datasetstr

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
datasetstr

The dataset id.

fidstr

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
datasetstr

The dataset id.

namestr, optional

The name of the dataset.

descriptionstr, 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
datasetstr

The dataset id.

fidstr

The feature id.

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

featuredict

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: 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'
property 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
featuresiterable

An collection of GeoJSON features

profilestr

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

alternativesbool

Whether to try to return alternative routes, default: False

geometriesstring

Type of geometry returned (geojson, polyline, polyline6)

overviewstring or False

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

stepsbool

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

continue_straightbool

Direction of travel when departing intermediate waypoints

radiusesiterable of numbers or ‘unlimited’

Must be same length as features

waypoint_snappinglist

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)

annotationsstr

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 ‘,’.

languagestr

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: 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'
property 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/search/#geocoding.

property 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/search/#reverse-geocoding.

mapbox.services.mapmatching module

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

Bases: 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: 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'
property 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
coordinatessequence

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

profilestr

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

annotationslist

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

sourceslist

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

destinationslist

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).
codestr

Status of the response

sourceslist

Results of snapping selected coordinates to the nearest addresses.

destinationslist

Results of snapping selected coordinates to the nearest addresses.

durationslist

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.

distanceslist

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: 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'
property 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: 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: Service

Access to Tilequery API V4

Attributes
api_namestr

The API’s name.

api_versionstr

The API’s version number.

valid_geometrieslist

The possible values for geometry.

base_uristr

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'
property 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_idstr 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.

lonfloat

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

latfloat

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

radiusint, 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.

limitint, 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.

dedupebool, optional

Whether to remove duplicate results.

If None, the default value is True.

geometrystr, optional

The geometry type to query.

layerslist, 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: 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, bypass])

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, ...])

Upload data and create a Mapbox tileset

api_name = 'uploads'
api_version = 'v1'
create(stage_url, tileset, name=None, patch=False, bypass=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.

bypass: bool

Optional bypass validation mode for MBTiles 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’.

usernamestr

Account username, defaults to the service’s username.

accountstr, 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
usernamestr

Account username, defaults to the service’s username.

accountstr, 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’.

usernamestr

Account username, defaults to the service’s username.

accountstr, deprecated

Alias for username. Will be removed in version 1.0.

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

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.

bypass: bool

Optional bypass validation mode for MBTiles 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