Mapbox Python SDK
The Mapbox Python SDK is an official client library for interacting with various Mapbox APIs, including Geocoding, Directions, Matrix, Static Images, and Uploads. It simplifies API requests and response handling. The current version is 0.18.1, and it maintains an active development cadence with regular updates addressing API changes and new features.
Common errors
-
ModuleNotFoundError: No module named 'mapbox'
cause The 'mapbox' package is not installed in your current Python environment.fixRun `pip install mapbox` to install the library. -
mapbox.errors.InvalidAccessTokenError: Unauthorized - Invalid Token
cause The Mapbox access token provided is either incorrect, expired, or does not have sufficient permissions for the requested API. A common cause is using a public (pk.) token for a server-side API that requires a secret (sk.) token.fixDouble-check your `MAPBOX_ACCESS_TOKEN` for typos. Ensure it is a *secret* token (`sk.`) and has the required scopes enabled for the specific Mapbox API you are calling (e.g., `geocoding:forward` for Geocoding). You can generate/manage tokens in your Mapbox account dashboard. -
AttributeError: 'module' object has no attribute 'Geocoder'
cause You likely imported the entire `mapbox` module (e.g., `import mapbox`) and then tried to access a service client like `mapbox.Geocoder()`. The service clients are meant to be imported directly.fixChange your import statement to `from mapbox import Geocoder` (and other service clients you need, e.g., `Directions`, `Matrix`). -
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))cause This error can occur if there's a problem with the network connection, a proxy issue, or if the Mapbox API rejects the request very early (e.g., due to malformed headers, extremely rapid requests triggering rate limits, or invalid token even before a proper HTTP response).fixCheck your internet connection and any proxy settings. If occurring frequently, verify your `MAPBOX_ACCESS_TOKEN` is correct and not rate-limited. Implement retry logic for transient network issues. If using a custom Mapbox host, ensure it's correctly configured.
Warnings
- breaking The `Distance` API was deprecated and removed in favor of the more comprehensive `Matrix` API.
- gotcha Using the wrong type of Mapbox access token for server-side APIs (e.g., Geocoding, Directions). Many Mapbox services require a *secret* access token (starting with `sk.`) for server-side requests, while *public* tokens (starting with `pk.`) are typically for client-side map display and have limited API access.
- breaking As the library is pre-1.0 (currently 0.x.x), minor version updates (e.g., from 0.17.x to 0.18.x) *can* introduce breaking changes without a major version bump, deviating from strict semantic versioning.
Install
-
pip install mapbox
Imports
- Geocoder
import mapbox; client = mapbox.Geocoder()
from mapbox import Geocoder
- Directions
from mapbox import Directions
- Matrix
from mapbox import Matrix
- Static
from mapbox import Static
- Uploads
from mapbox import Uploads
- Mapbox
from mapbox import Mapbox
Quickstart
import os
from mapbox import Geocoder
# Ensure your Mapbox access token is set as an environment variable (e.g., export MAPBOX_ACCESS_TOKEN="sk.YOUR_SECRET_TOKEN")
# For server-side APIs like Geocoding, a secret (sk.) token is usually required.
access_token = os.environ.get('MAPBOX_ACCESS_TOKEN', 'YOUR_MAPBOX_SECRET_TOKEN')
if access_token == 'YOUR_MAPBOX_SECRET_TOKEN':
print("WARNING: MAPBOX_ACCESS_TOKEN environment variable not set or placeholder used.\nPlease set it to your actual Mapbox secret access token for the quickstart to function.")
# Using a dummy token for code structure, this will fail API calls.
access_token = "sk.dummy_token_for_example"
geocoder = Geocoder(access_token=access_token)
# Perform a forward geocode lookup
response = geocoder.forward('1600 Amphitheatre Pkwy, Mountain View, CA')
if response.status_code == 200:
data = response.json()
if data and data.get('features'):
first_result = data['features'][0]
print(f"Location: {first_result['place_name']}")
print(f"Coordinates (lon, lat): {first_result['center']}")
else:
print("No features found.")
else:
print(f"Error: {response.status_code} - {response.json().get('message', 'Unknown error')}")