Mapbox Python SDK

0.18.1 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Mapbox Geocoder client using an access token from an environment variable and perform a basic forward geocode lookup. For server-side APIs, ensure you use a secret (sk.) access token with appropriate scopes.

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')}")

view raw JSON →