oslew docs
Console
Menu

Clients

Python
pip install oslew
TypeScript
npm install @oslew/client

Both 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

Python
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)
TypeScript
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_KEY environment variable when the argument is absent. With neither, requests go without one: /v1/health and /v1/migrate answer, everything else is 401. The key is sent as Authorization: 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, timeout in seconds in Python and timeoutMs in milliseconds in TypeScript.
  • Every request says who it is: User-Agent: oslew-python/<version> oroslew-typescript/<version>. Both packages export it as USER_AGENT.

Calling a method

  • The method is the route's operationId: /v1/geocode is geocode, /v1/batch/{id}/results is batch_results. Where two methods share a path, the second is prefixed with its verb: validate and post_validate, traffic and post_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_m is radius_m in both — with two exceptions where the name is a reserved word: Python spells the from parameter from_, and the TypeScript method for /v1/static is static_.
  • A request body is the first argument of post_validate, match, locate and post_traffic (a dict or object, sent as JSON), of batch (the file as text or bytes; content_type / contentType says what it is, application/x-ndjson by default) and of post_transit_rt (protobuf bytes).
  • Booleans go on the wire as true and false; an argument left out is not sent at all, so the route's own default applies.
Python
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)
TypeScript
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 answersPythonTypeScript
JSONThe parsed value: a dict, typed as a TypedDict so an editor completes field namesThe 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 themRecord<string, unknown>, or an array of them
CSV or NDJSON (batch_results)strstring
An image or a tile (static, tiles)bytesUint8Array

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.

StatusClassRetry?
400BadRequestNo: change the request.
401AuthErrorNo: the key.
403PlanErrorNo: the message names the plan that includes the product.
404NotFoundNo.
429RateLimitedYes, after Retry-After.
503UnavailableYes.
no answerTransportError, status 0: a refused connection, an unknown host, the timeoutIf the request is safe to repeat.
anything elseGeoError — a batch job's 409, a 413, 415, 422 or 500Depends.

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.

Python
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)
TypeScript
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.

Python
# 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)
TypeScript
// 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:

curl
curl -X DELETE -H "Authorization: Bearer $GEO_API_KEY" \
  "https://api.oslew.com/v1/batch/$JOB_ID"
Python
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"}
TypeScript
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.

RoutePythonTypeScriptReturns
GET /compat/google/maps/api/geocode/jsoncompat_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.phpcompat_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.phpcompat_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/reversecompat_nominatim_reverse(lat, lon, *, format=None) -> Dict[str, Any]compat_nominatim_reverse(lat, lon, options?) => Record<string, unknown>parsed JSON
GET /compat/nominatim/searchcompat_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/adminadmin(at) -> AdminResponseadmin(at) => AdminResponseparsed JSON
GET /v1/aggregateaggregate(at, *, in_level=None, level=None, from_=None, to=None, bucket=None, limit=None) -> AggregateResponseaggregate(at, options?) => AggregateResponseparsed JSON
GET /v1/autocompleteautocomplete(q, *, near=None, stream=None, limit=None) -> AutocompleteResponseautocomplete(q, options?) => AutocompleteResponseparsed JSON
GET /v1/batchlist_batches(*, limit=None) -> BatchListlist_batches(options?) => BatchListparsed JSON
POST /v1/batchbatch(body, *, format=None) -> BatchJobbatch(body, options?) => BatchJobparsed JSON
GET /v1/batch/{id}get_batch(id) -> BatchJobget_batch(id) => BatchJobparsed JSON
GET /v1/batch/{id}/resultsbatch_results(id, *, format=None) -> strbatch_results(id, options?) => stringtext
GET /v1/conditionsconditions(at, *, radius_m=None) -> ConditionsResponseconditions(at, options?) => ConditionsResponseparsed JSON
GET /v1/crossingscrossings(mmsi, *, from_=None, to=None, zones=None) -> CrossingsResponsecrossings(mmsi, options?) => CrossingsResponseparsed JSON
GET /v1/departuresdepartures(*, stop=None, at=None, time=None, limit=None) -> DeparturesResponsedepartures(options?) => DeparturesResponseparsed JSON
GET /v1/elevationelevation(*, at=None, path=None, samples=None) -> ElevationResponseelevation(options?) => ElevationResponseparsed JSON
GET /v1/eventsevents(*, at=None, bbox=None, radius_m=None, from_=None, to=None, category=None, q=None, order=None, limit=None) -> EventsResponseevents(options?) => EventsResponseparsed JSON
POST /v1/feedbackfeedback(body) -> FeedbackResultfeedback(body) => FeedbackResultparsed JSON
GET /v1/geocodegeocode(q, *, near=None, country=None, license=None, epoch=None, release=None, receipt=None, limit=None, interpolate=None) -> GeocodeResponsegeocode(q, options?) => GeocodeResponseparsed JSON
GET /v1/healthhealth() -> Healthhealth() => Healthparsed JSON
GET /v1/herehere(at, *, radius_m=None, limit=None, time=None) -> HereResponsehere(at, options?) => HereResponseparsed JSON
GET /v1/isochroneisochrone(at, *, seconds=None, level=None, profile=None, traffic=None) -> IsochroneResponseisochrone(at, options?) => IsochroneResponseparsed JSON
GET /v1/journeysjourneys(from_, to, *, time=None, max_transfers=None, walk_m=None, limit=None) -> JourneysResponsejourneys(from, to, options?) => JourneysResponseparsed JSON
POST /v1/locatelocate(body) -> LocateResponselocate(body) => LocateResponseparsed JSON
POST /v1/matchmatch(body) -> MatchResponsematch(body) => MatchResponseparsed JSON
GET /v1/matrixmatrix(points, *, profile=None, traffic=None) -> MatrixResponsematrix(points, options?) => MatrixResponseparsed JSON
GET /v1/migratemigrate(url, *, volume=None, peak_rps=None, base=None) -> MigrateResponsemigrate(url, options?) => MigrateResponseparsed JSON
GET /v1/nearbynearby(at, *, category=None, q=None, open_at=None, limit=None) -> NearbyResponsenearby(at, options?) => NearbyResponseparsed JSON
GET /v1/observationsobservations(at, parameter, *, from_=None, to=None, stations=None, radius_m=None) -> ObservationsResponseobservations(at, parameter, options?) => ObservationsResponseparsed JSON
GET /v1/optimizeoptimize(points, *, roundtrip=None, source=None, destination=None, profile=None, traffic=None, geometry=None) -> OptimizeResponseoptimize(points, options?) => OptimizeResponseparsed JSON
GET /v1/postcodepostcode(code, *, country=None, prefix=None, limit=None) -> PostcodeResponsepostcode(code, options?) => PostcodeResponseparsed JSON
GET /v1/rasterraster(layer, *, time=None, at=None, path=None, samples=None) -> RasterResponseraster(layer, options?) => RasterResponseparsed JSON
GET /v1/reversereverse(at, *, limit=None) -> ReverseResponsereverse(at, options?) => ReverseResponseparsed JSON
GET /v1/routeroute(from_, to, *, geometry=None, profile=None, traffic=None) -> RouteResponseroute(from, to, options?) => RouteResponseparsed JSON
GET /v1/scenesscenes(*, bbox=None, at=None, from_=None, to=None, max_cloud=None, limit=None) -> ScenesResponsescenes(options?) => ScenesResponseparsed JSON
GET /v1/slasla() -> Dict[str, Any]sla() => Record<string, unknown>parsed JSON
GET /v1/snapsnap(at, *, profile=None) -> SnapResponsesnap(at, options?) => SnapResponseparsed JSON
GET /v1/staticstatic(at, *, zoom=None, width=None, height=None) -> bytesstatic_(at, options?) => Uint8Arraybytes
GET /v1/stopsstops(at, *, radius_m=None, limit=None) -> StopsResponsestops(at, options?) => StopsResponseparsed JSON
GET /v1/style.jsonstyle_json() -> Dict[str, Any]style_json() => Record<string, unknown>parsed JSON
GET /v1/tiles.jsontiles_json() -> Dict[str, Any]tiles_json() => Record<string, unknown>parsed JSON
GET /v1/tiles/{z}/{x}/{y}tiles(z, x, y) -> bytestiles(z, x, y) => Uint8Arraybytes
GET /v1/timezonetimezone(at, *, timestamp=None) -> TimezoneResponsetimezone(at, options?) => TimezoneResponseparsed JSON
GET /v1/tracktrack(mmsi, *, from_=None, to=None) -> TrackResponsetrack(mmsi, options?) => TrackResponseparsed JSON
GET /v1/traffictraffic() -> TrafficStatustraffic() => TrafficStatusparsed JSON
POST /v1/trafficpost_traffic(body, *, format=None) -> TrafficStatuspost_traffic(body, options?) => TrafficStatusparsed JSON
GET /v1/transit_rttransit_rt() -> List[TransitRtStatus]transit_rt() => TransitRtStatus[]parsed JSON
POST /v1/transit_rtpost_transit_rt(body) -> TransitRtStatuspost_transit_rt(body) => TransitRtStatusparsed JSON
GET /v1/validatevalidate(*, text=None, house_number=None, street=None, locality=None, region=None, postcode=None, country=None) -> ValidateResponsevalidate(options?) => ValidateResponseparsed JSON
POST /v1/validatepost_validate(body) -> ValidateResponsepost_validate(body) => ValidateResponseparsed JSON
POST /v1/validate/commitvalidate_commit(body) -> ValidateResponsevalidate_commit(body) => ValidateResponseparsed JSON
GET /v1/vesselvessel(mmsi) -> VesselResponsevessel(mmsi) => VesselResponseparsed JSON
GET /v1/vesselsvessels(at, *, level=None, from_=None, to=None, limit=None) -> VesselsResponsevessels(at, options?) => VesselsResponseparsed 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.

shell
curl -H "Authorization: Bearer $GEO_API_KEY" \
  "https://api.oslew.com/v1/geocode?q=Museo+Soumaya"