Clients
pip install oslewnpm install @oslew/clientBoth clients are generated from the same OpenAPI document the reference is rendered from, version 0.0.1: one method per GET and POST route, named after itsoperationId, and one type per schema. Neither is edited by hand, so neither can describe a route the service does not serve.
Neither has any dependencies. The Python client is urllib, json anddataclasses from the standard library, on Python 3.9 or later, so installing it cannot move a version of anything else in your environment. The TypeScript client is fetch and nothing else.
Making a client
from oslew import Client
# Client(api_key=None, *, base_url="https://api.oslew.com", timeout=30.0)
client = Client(base_url="https://api.oslew.com") # the key from GEO_API_KEY
client = Client("sk_live_…", base_url="https://api.oslew.com", timeout=10.0)import { Client } from "@oslew/client";
// new Client({ apiKey?, baseUrl?, timeoutMs?, fetch? })
const client = new Client({ baseUrl: "https://api.oslew.com" }); // the key from GEO_API_KEY
const other = new Client({
apiKey: "sk_live_…",
baseUrl: "https://api.oslew.com",
timeoutMs: 10_000,
fetch: myFetch, // a proxy, a test double, or a runtime whose fetch is elsewhere
});- The key is the argument, or the
GEO_API_KEYenvironment variable when the argument is absent. With neither, requests go without one:/v1/healthand/v1/migrateanswer, everything else is401. The key is sent asAuthorization: Bearer …, and never in a URL. - The base URL defaults to
https://api.oslew.com; a trailing slash is dropped. - The timeout covers each request: 30 seconds by default,
timeoutin seconds in Python andtimeoutMsin milliseconds in TypeScript. - Every request says who it is:
User-Agent: oslew-python/<version>oroslew-typescript/<version>. Both packages export it asUSER_AGENT.
Calling a method
- The method is the route's
operationId:/v1/geocodeisgeocode,/v1/batch/{id}/resultsisbatch_results. Where two methods share a path, the second is prefixed with its verb:validateandpost_validate,trafficandpost_traffic. - Required parameters are positional, path parameters first, in the order the document declares them.
- Optional parameters are keyword arguments in Python and one trailing options object in TypeScript, so adding an optional parameter to a route never moves an argument you already pass.
- Names are the API's own —
radius_misradius_min both — with two exceptions where the name is a reserved word: Python spells thefromparameterfrom_, and the TypeScript method for/v1/staticisstatic_. - A request body is the first argument of
post_validate,match,locateandpost_traffic(a dict or object, sent as JSON), ofbatch(the file as text or bytes;content_type/contentTypesays what it is,application/x-ndjsonby default) and ofpost_transit_rt(protobuf bytes). - Booleans go on the wire as
trueandfalse; an argument left out is not sent at all, so the route's own default applies.
answer = client.geocode("Avenida Insurgentes Sur 1602, 03940", limit=3)
route = client.route("19.4406,-99.2047", "19.4326,-99.1332", profile="walking")
track = client.track(338118417, from_=1672531200, to=1672534800)
png = client.static("19.4326,-99.1332", zoom=15)const answer = await client.geocode("Avenida Insurgentes Sur 1602, 03940", { limit: 3 });
const route = await client.route("19.4406,-99.2047", "19.4326,-99.1332", { profile: "walking" });
const track = await client.track(338118417, { from: 1672531200, to: 1672534800 });
const png = await client.static_("19.4326,-99.1332", { zoom: 15 });What a method returns
The content type the route declares decides it; no method guesses.
| The route answers | Python | TypeScript |
|---|---|---|
| JSON | The parsed value: a dict, typed as a TypedDict so an editor completes field names | The parsed value, typed as an interface with required fields required |
| JSON in a vendor's shape (the compatibility routes) | Dict[str, Any], or a list of them | Record<string, unknown>, or an array of them |
CSV or NDJSON (batch_results) | str | string |
An image or a tile (static, tiles) | bytes | Uint8Array |
Every schema in the document is a named type, and so are rows the document declares inline, so one row of an answer can be held in a typed variable: GeocodeResponse, Resolved,PostcodeResponseResults. A tile address with no tile answers 204, which comes back as empty bytes.
When a request is refused
Every refusal raises or throws its own class, all subclasses of GeoError, because they mean different things and only some are worth retrying. See errors for what each status means.
| Status | Class | Retry? |
|---|---|---|
400 | BadRequest | No: change the request. |
401 | AuthError | No: the key. |
403 | PlanError | No: the message names the plan that includes the product. |
404 | NotFound | No. |
429 | RateLimited | Yes, after Retry-After. |
503 | Unavailable | Yes. |
| no answer | TransportError, status 0: a refused connection, an unknown host, the timeout | If the request is safe to repeat. |
| anything else | GeoError — a batch job's 409, a 413, 415, 422 or 500 | Depends. |
Each carries status, message — the service's error sentence, or the start of a plain-text refusal from the framework — body, the parsed JSON body ({} when it was not JSON; a batch 409's done, rows and remaining_s are here),url, and the rate-limit values as rate_limit / rateLimit, withretry_after / retryAfter as a shortcut. The Python classes also keep the answer'sheaders, lower-cased.
from oslew import Client, PlanError, RateLimited, GeoError
try:
answer = client.route(a, b)
except PlanError as e:
print(e.message) # the plan that includes routing
except RateLimited as e:
print(e.retry_after) # seconds until a token is back
except GeoError as e:
print(e.status, e.body)import { PlanError, RateLimited, GeoError } from "@oslew/client";
try {
const answer = await client.route(a, b);
} catch (e) {
if (e instanceof PlanError) console.log(e.message); // the plan that includes routing
else if (e instanceof RateLimited) console.log(e.retryAfter); // seconds until a token is back
else if (e instanceof GeoError) console.log(e.status, e.body);
else throw e;
}Rate limits
After every answer — admitted or refused — client.rate_limit (Python) or client.rateLimit(TypeScript) holds what its headers said: limit (the sustained rate), remaining (whole tokens left), reset (seconds until the bucket is full) and retry_after /retryAfter (only on a 429). Each is None / null when the answer did not carry it, as the keyless routes' answers do not. Both spellings of the headers are read. Seerate limits.
Each client has an opt-in helper that waits out Retry-After and tries again. It retries onlyRateLimited; anything else is raised at once, because no amount of waiting turns a 403into a 200.
# retry_on_rate_limit(call, *args, attempts=3, max_sleep=60.0, sleep=time.sleep, **kwargs)
from oslew import retry_on_rate_limit
answer = retry_on_rate_limit(client.geocode, "Museo Soumaya", attempts=5)// retryOnRateLimit<T>(call: () => Promise<T>, { attempts = 3, maxSleepMs = 60_000, sleep? } = {}): Promise<T>
import { retryOnRateLimit } from "@oslew/client";
const answer = await retryOnRateLimit(() => client.geocode("Museo Soumaya"), { attempts: 5 });attempts counts the first try. A wait is Retry-After seconds, one second when the header is missing, and never longer than max_sleep / maxSleepMs. When the attempts run out, the last RateLimited is raised. sleep is there for tests.
What is not generated
The DELETE routes have no methods, on purpose: they cancel a batch job and throw its results away, or clear a feed an operator loaded, and a client that can do that by accident is worse than one that cannot. When it is what you mean, send it yourself:
- DELETE
/v1/batch/{id}— Cancel a batch job and throw its payloads away. - DELETE
/v1/traffic— Discard the live weights. - DELETE
/v1/transit_rt— Drop every live transit delay.
curl -X DELETE -H "Authorization: Bearer $GEO_API_KEY" \
"https://api.oslew.com/v1/batch/$JOB_ID"import os, json, urllib.request
request = urllib.request.Request(
f"https://api.oslew.com/v1/batch/{job_id}",
method="DELETE",
headers={"Authorization": "Bearer " + os.environ["GEO_API_KEY"]},
)
with urllib.request.urlopen(request) as answer:
print(json.load(answer)) # {"id": ..., "state": "cancelled"}const answer = await fetch(`https://api.oslew.com/v1/batch/${jobId}`, {
method: "DELETE",
headers: { Authorization: `Bearer ${process.env.GEO_API_KEY}` },
});
console.log(await answer.json()); // { id, state: "cancelled" }Cancelling a batch job deletes its input and every result part; see batch jobs. The operator routes are in operator feeds.
Every method
Generated from the signatures the clients' generator prints, one row per operation, 54 in all. Each links to its reference page.
| Route | Python | TypeScript | Returns |
|---|---|---|---|
GET /compat/google/maps/api/geocode/json | compat_google_maps_api_geocode_json(*, address=None, latlng=None, key=None, language=None, components=None, limit=None) -> Dict[str, Any] | compat_google_maps_api_geocode_json(options?) => Record<string, unknown> | parsed JSON |
GET /compat/locationiq/v1/reverse.php | compat_locationiq_v1_reverse_php(lat, lon, *, key=None, format=None) -> Dict[str, Any] | compat_locationiq_v1_reverse_php(lat, lon, options?) => Record<string, unknown> | parsed JSON |
GET /compat/locationiq/v1/search.php | compat_locationiq_v1_search_php(q, *, key=None, format=None, limit=None, addressdetails=None) -> List[Dict[str, Any]] | compat_locationiq_v1_search_php(q, options?) => (Record<string, unknown>)[] | parsed JSON |
GET /compat/mapbox/geocoding/v5/mapbox.places/{search_text} | compat_mapbox_geocoding_v5_mapbox_places(search_text, *, limit=None, proximity=None, country=None, access_token=None) -> Dict[str, Any] | compat_mapbox_geocoding_v5_mapbox_places(search_text, options?) => Record<string, unknown> | parsed JSON |
GET /compat/nominatim/reverse | compat_nominatim_reverse(lat, lon, *, format=None) -> Dict[str, Any] | compat_nominatim_reverse(lat, lon, options?) => Record<string, unknown> | parsed JSON |
GET /compat/nominatim/search | compat_nominatim_search(q, *, format=None, limit=None, addressdetails=None, countrycodes=None) -> List[Dict[str, Any]] | compat_nominatim_search(q, options?) => (Record<string, unknown>)[] | parsed JSON |
GET /v1/admin | admin(at) -> AdminResponse | admin(at) => AdminResponse | parsed JSON |
GET /v1/aggregate | aggregate(at, *, in_level=None, level=None, from_=None, to=None, bucket=None, limit=None) -> AggregateResponse | aggregate(at, options?) => AggregateResponse | parsed JSON |
GET /v1/autocomplete | autocomplete(q, *, near=None, stream=None, limit=None) -> AutocompleteResponse | autocomplete(q, options?) => AutocompleteResponse | parsed JSON |
GET /v1/batch | list_batches(*, limit=None) -> BatchList | list_batches(options?) => BatchList | parsed JSON |
POST /v1/batch | batch(body, *, format=None) -> BatchJob | batch(body, options?) => BatchJob | parsed JSON |
GET /v1/batch/{id} | get_batch(id) -> BatchJob | get_batch(id) => BatchJob | parsed JSON |
GET /v1/batch/{id}/results | batch_results(id, *, format=None) -> str | batch_results(id, options?) => string | text |
GET /v1/conditions | conditions(at, *, radius_m=None) -> ConditionsResponse | conditions(at, options?) => ConditionsResponse | parsed JSON |
GET /v1/crossings | crossings(mmsi, *, from_=None, to=None, zones=None) -> CrossingsResponse | crossings(mmsi, options?) => CrossingsResponse | parsed JSON |
GET /v1/departures | departures(*, stop=None, at=None, time=None, limit=None) -> DeparturesResponse | departures(options?) => DeparturesResponse | parsed JSON |
GET /v1/elevation | elevation(*, at=None, path=None, samples=None) -> ElevationResponse | elevation(options?) => ElevationResponse | parsed JSON |
GET /v1/events | events(*, at=None, bbox=None, radius_m=None, from_=None, to=None, category=None, q=None, order=None, limit=None) -> EventsResponse | events(options?) => EventsResponse | parsed JSON |
POST /v1/feedback | feedback(body) -> FeedbackResult | feedback(body) => FeedbackResult | parsed JSON |
GET /v1/geocode | geocode(q, *, near=None, country=None, license=None, epoch=None, release=None, receipt=None, limit=None, interpolate=None) -> GeocodeResponse | geocode(q, options?) => GeocodeResponse | parsed JSON |
GET /v1/health | health() -> Health | health() => Health | parsed JSON |
GET /v1/here | here(at, *, radius_m=None, limit=None, time=None) -> HereResponse | here(at, options?) => HereResponse | parsed JSON |
GET /v1/isochrone | isochrone(at, *, seconds=None, level=None, profile=None, traffic=None) -> IsochroneResponse | isochrone(at, options?) => IsochroneResponse | parsed JSON |
GET /v1/journeys | journeys(from_, to, *, time=None, max_transfers=None, walk_m=None, limit=None) -> JourneysResponse | journeys(from, to, options?) => JourneysResponse | parsed JSON |
POST /v1/locate | locate(body) -> LocateResponse | locate(body) => LocateResponse | parsed JSON |
POST /v1/match | match(body) -> MatchResponse | match(body) => MatchResponse | parsed JSON |
GET /v1/matrix | matrix(points, *, profile=None, traffic=None) -> MatrixResponse | matrix(points, options?) => MatrixResponse | parsed JSON |
GET /v1/migrate | migrate(url, *, volume=None, peak_rps=None, base=None) -> MigrateResponse | migrate(url, options?) => MigrateResponse | parsed JSON |
GET /v1/nearby | nearby(at, *, category=None, q=None, open_at=None, limit=None) -> NearbyResponse | nearby(at, options?) => NearbyResponse | parsed JSON |
GET /v1/observations | observations(at, parameter, *, from_=None, to=None, stations=None, radius_m=None) -> ObservationsResponse | observations(at, parameter, options?) => ObservationsResponse | parsed JSON |
GET /v1/optimize | optimize(points, *, roundtrip=None, source=None, destination=None, profile=None, traffic=None, geometry=None) -> OptimizeResponse | optimize(points, options?) => OptimizeResponse | parsed JSON |
GET /v1/postcode | postcode(code, *, country=None, prefix=None, limit=None) -> PostcodeResponse | postcode(code, options?) => PostcodeResponse | parsed JSON |
GET /v1/raster | raster(layer, *, time=None, at=None, path=None, samples=None) -> RasterResponse | raster(layer, options?) => RasterResponse | parsed JSON |
GET /v1/reverse | reverse(at, *, limit=None) -> ReverseResponse | reverse(at, options?) => ReverseResponse | parsed JSON |
GET /v1/route | route(from_, to, *, geometry=None, profile=None, traffic=None) -> RouteResponse | route(from, to, options?) => RouteResponse | parsed JSON |
GET /v1/scenes | scenes(*, bbox=None, at=None, from_=None, to=None, max_cloud=None, limit=None) -> ScenesResponse | scenes(options?) => ScenesResponse | parsed JSON |
GET /v1/sla | sla() -> Dict[str, Any] | sla() => Record<string, unknown> | parsed JSON |
GET /v1/snap | snap(at, *, profile=None) -> SnapResponse | snap(at, options?) => SnapResponse | parsed JSON |
GET /v1/static | static(at, *, zoom=None, width=None, height=None) -> bytes | static_(at, options?) => Uint8Array | bytes |
GET /v1/stops | stops(at, *, radius_m=None, limit=None) -> StopsResponse | stops(at, options?) => StopsResponse | parsed JSON |
GET /v1/style.json | style_json() -> Dict[str, Any] | style_json() => Record<string, unknown> | parsed JSON |
GET /v1/tiles.json | tiles_json() -> Dict[str, Any] | tiles_json() => Record<string, unknown> | parsed JSON |
GET /v1/tiles/{z}/{x}/{y} | tiles(z, x, y) -> bytes | tiles(z, x, y) => Uint8Array | bytes |
GET /v1/timezone | timezone(at, *, timestamp=None) -> TimezoneResponse | timezone(at, options?) => TimezoneResponse | parsed JSON |
GET /v1/track | track(mmsi, *, from_=None, to=None) -> TrackResponse | track(mmsi, options?) => TrackResponse | parsed JSON |
GET /v1/traffic | traffic() -> TrafficStatus | traffic() => TrafficStatus | parsed JSON |
POST /v1/traffic | post_traffic(body, *, format=None) -> TrafficStatus | post_traffic(body, options?) => TrafficStatus | parsed JSON |
GET /v1/transit_rt | transit_rt() -> List[TransitRtStatus] | transit_rt() => TransitRtStatus[] | parsed JSON |
POST /v1/transit_rt | post_transit_rt(body) -> TransitRtStatus | post_transit_rt(body) => TransitRtStatus | parsed JSON |
GET /v1/validate | validate(*, text=None, house_number=None, street=None, locality=None, region=None, postcode=None, country=None) -> ValidateResponse | validate(options?) => ValidateResponse | parsed JSON |
POST /v1/validate | post_validate(body) -> ValidateResponse | post_validate(body) => ValidateResponse | parsed JSON |
POST /v1/validate/commit | validate_commit(body) -> ValidateResponse | validate_commit(body) => ValidateResponse | parsed JSON |
GET /v1/vessel | vessel(mmsi) -> VesselResponse | vessel(mmsi) => VesselResponse | parsed JSON |
GET /v1/vessels | vessels(at, *, level=None, from_=None, to=None, limit=None) -> VesselsResponse | vessels(at, options?) => VesselsResponse | parsed JSON |
Or no client
The API is HTTP and JSON; a client is a convenience, not a requirement. Every example in these docs shows the curl alongside the Python and TypeScript.
curl -H "Authorization: Bearer $GEO_API_KEY" \
"https://api.oslew.com/v1/geocode?q=Museo+Soumaya"