Distance Matrix API in Python: requests, httpx and asyncio
Call a distance matrix API from Python the right way: one request, tiling large matrices, async fan-out with limits, retries with Retry-After and pandas output.
By Wayline Engineering · · Updated · 4 min read
A distance matrix API returns the road distance and drive time between every origin and every destination you send, in one request. In Python you need about ten lines for the first call, and a little more care once matrices get large: tiling to stay under the per-request element limit, bounded concurrency, and retries that respect Retry-After. This guide covers all three with plain requests, httpx and asyncio.
The examples call the Wayline Distance Matrix API (POST /v1/matrix). Coordinates are lat,lng objects, and the API key comes from an environment variable.
1. The smallest working request (requests)
import os
import requests
API = "https://api.wayline.cloud"
HEADERS = {"Authorization": f"Bearer {os.environ['WAYLINE_API_KEY']}"}
# Example points in Dhaka (Bangladesh is covered today; use points in an enabled region)
origins = [(23.7925, 90.4078), (23.7639, 90.3889)] # Gulshan, Tejgaon
destinations = [(23.7330, 90.4172), (23.7465, 90.3760)] # Motijheel, Dhanmondi
res = requests.post(
f"{API}/v1/matrix",
headers=HEADERS,
json={
"origins": [{"lat": a, "lng": b} for a, b in origins],
"destinations": [{"lat": a, "lng": b} for a, b in destinations],
},
timeout=15,
)
res.raise_for_status()
data = res.json()
for i, row in enumerate(data["rows"]):
for j, el in enumerate(row["elements"]):
if el["status"] == "OK":
print(i, j, el["distance_meters"] / 1000, "km", round(el["duration_seconds"] / 60), "min")
else:
print(i, j, el["status"]) # e.g. NO_ROUTETwo things to notice:
- Always check each element's
status. A matrix can succeed as a whole while one pair has no route (an island without a ferry in the data, for example). - Billing is per element. A 2 × 2 matrix is 4 units. The
X-Units-Chargedresponse header tells you exactly what you paid for. Errors (4xx/5xx) are never billed.
2. Load it into pandas
Most matrix work ends up in a DataFrame:
import pandas as pd
km = pd.DataFrame(
[[el.get("distance_meters", float("nan")) / 1000 for el in row["elements"]] for row in data["rows"]],
index=["Gulshan", "Tejgaon"],
columns=["Motijheel", "Dhanmondi"],
)
print(km.round(1))Use the duration matrix (duration_seconds) when you assign work by time, such as nearest driver or delivery zones, and the distance matrix when you bill or reimburse by distance.
3. Tile large matrices
Every API caps the number of elements per request (ours is published on the pricing page). A 300 × 300 matrix is 90,000 elements, so split it into tiles and stitch the results:
from itertools import product
def tiles(n_orig: int, n_dest: int, max_elements: int):
"""Yield (orig_slice, dest_slice) blocks that each fit under max_elements."""
side = int(max_elements ** 0.5)
for oi, di in product(range(0, n_orig, side), range(0, n_dest, side)):
yield slice(oi, min(oi + side, n_orig)), slice(di, min(di + side, n_dest))Square tiles keep the number of requests low. Each tile is independent, which makes it a natural fit for concurrency.
4. Concurrency with httpx and asyncio
import asyncio
import os
import random
import httpx
API = "https://api.wayline.cloud"
MAX_IN_FLIGHT = 4 # stay well under your plan's requests-per-second limit
async def post_with_retry(client: httpx.AsyncClient, body: dict, attempts: int = 5) -> dict:
for attempt in range(attempts):
r = await client.post("/v1/matrix", json=body)
if r.status_code == 429 or r.status_code >= 500:
retry_after = float(r.headers.get("Retry-After", 0)) or min(8, 0.5 * 2 ** attempt)
await asyncio.sleep(retry_after + random.uniform(0, 0.25)) # jitter
continue
r.raise_for_status() # 4xx other than 429: a bug in the request, do not retry
return r.json()
raise RuntimeError("matrix request failed after retries")
async def full_matrix(origins, destinations, max_elements: int):
sem = asyncio.Semaphore(MAX_IN_FLIGHT)
out = [[None] * len(destinations) for _ in origins]
async with httpx.AsyncClient(
base_url=API,
headers={"Authorization": f"Bearer {os.environ['WAYLINE_API_KEY']}"},
timeout=30,
) as client:
async def run(os_, ds_):
async with sem:
body = {
"origins": [{"lat": a, "lng": b} for a, b in origins[os_]],
"destinations": [{"lat": a, "lng": b} for a, b in destinations[ds_]],
}
data = await post_with_retry(client, body)
for i, row in enumerate(data["rows"]):
for j, el in enumerate(row["elements"]):
out[os_.start + i][ds_.start + j] = el
await asyncio.gather(*(run(o, d) for o, d in tiles(len(origins), len(destinations), max_elements)))
return outWhy these choices:
- A semaphore, not unbounded
gather. Firing 200 tiles at once just produces 429s. Retry-Afterfirst, exponential backoff with jitter second. Retrying a 400 is pointless; retrying a 429 immediately makes it worse. See errors and retries.- One shared client. Connection reuse matters more than anything else for latency.
5. Cache what does not change
Road distances between fixed points (warehouses, stores, customer addresses) change only when the map changes. Cache by rounded coordinates plus the map_version from the response, and you will pay for each pair once per map update rather than once per page view. The caching guide covers what is safe to keep.
6. Or use the SDK
If you would rather not maintain retry and tiling code, the Python SDK wraps the same endpoints with typed responses, retries and async support (pip install wayline).
Checklist
- Send
lat,lngobjects; check each element'sstatus. - Tile under the element limit; run tiles with bounded concurrency.
- Retry only 429 and 5xx, honoring
Retry-After. - Cache by coordinates +
map_version. - Use a free test key while developing; start here.