Python client reference
Blocking and async clients, typed requests, and result models.
Public classes and request types are exported by affordable_geo_apis.
Clients
GeocodingClient(*, base_url, api_key, **options)
AsyncGeocodingClient(*, base_url, api_key, **options)
# Blocking:
client.geocode(request, *, timeout=None) -> GeocodingResponse
client.search(request, *, timeout=None) -> GeocodingResponse
client.reverse_geocode(request, *, timeout=None) -> GeocodingResponse
client.autocomplete(request, *, timeout=None) -> AutocompleteResponse
client.resolve_autocomplete(suggestion, *, timeout=None) -> GeocodingResult
client.close() -> None
# Async: await each method.
async_client.geocode(request, *, timeout=None) -> GeocodingResponse
async_client.search(request, *, timeout=None) -> GeocodingResponse
client.search(request, *, timeout=None) -> GeocodingResponse
async_client.reverse_geocode(request, *, timeout=None) -> GeocodingResponse
async_client.autocomplete(request, *, timeout=None) -> AutocompleteResponse
async_client.resolve_autocomplete(suggestion, *, timeout=None) -> GeocodingResult
async_client.aclose() -> None
Blocking clients support with, async clients async with. Calls on a closed client raise RuntimeError. All constructor settings are keyword-only.
Constructor options
| Keyword | Type | Default / requirement |
|---|---|---|
base_url | str | Required HTTPS origin/prefix; loopback HTTP allowed |
api_key | str | Required nonempty key |
confidence_threshold | float | 0.8; finite number in [0, 1] |
fallbacks | Sequence of FallbackOptions or mappings | Empty sequence |
fallback_on | Sequence of FallbackTrigger, or None | None selects the five default triggers; [] replaces them |
fallback_budget | FallbackBudget, mapping, or None | Unlimited if None |
fallback_circuit_breaker | FallbackCircuitBreakerOptions, mapping, or None | Disabled if None |
timeout_ms | int | 10000; positive integer at most 2147483647 |
transport | httpx.AsyncBaseTransport or None | Default HTTPX transport; owned and closed by client |
Per-call timeout is an optional positive finite number of seconds across the complete provider chain. Its expiration raises TimeoutError.
Option dataclasses
| Dataclass | Fields |
|---|---|
FallbackOptions | provider: Literal['google', 'here'], api_key: str |
FallbackBudget | max_requests: int (nonnegative safe integer) |
FallbackCircuitBreakerOptions | failure_threshold: int, cooldown_ms: int (positive safe integers) |
These are frozen dataclasses. Equivalent mappings use the same field names. Invalid settings generally raise ValueError before networking.
Request TypedDicts
AddressRequest requires street: str (house number and street). Optional fields are city, state, zip, and country as strings, plus exclude_sources: list[str].
ReverseRequest requires lat: float and lon: float. Optional fields are country: str and exclude_sources: list[str].
SearchRequest requires q: str (1–256 characters). Optional fields are country: str, near: Point ({"lat": ..., "lon": ...}), limit: int (1–40, default 10), and exclude_sources: list[str]. Invalid values raise ValueError before networking.
Primary geocode requests require at least one nonempty city/state/ZIP. For geocode and reverse, country is a routing hint not sent to primary; search also sends it as a filter. See API validation.
Result models
GeocodingResult is a frozen dataclass with:
- Strings:
id,label,house_number,street(street name only),city,state,zip,country,match_type,source. type: ResultType:address,venue,street,zip,neighborhood,borough,city,county,state,country, or''.- Numbers:
lat,lon,confidence. provider: Provider.
Missing text fields are ''. match_type is primary-only (exact, interpolated, fallback).
Country is recognized ISO alpha-2 or ''. Confidence is in [0, 1], with 0 for unavailable values. to_dict() returns the fields as a dictionary.
GeocodingResponse is a frozen dataclass with results: list[GeocodingResult], provider: Provider, fallback_reason: FallbackReason | None, attempts: list[Attempt], and provider_response: dict[str, Any] | None.
Attempt is a frozen dataclass with provider, outcome, optional skip_reason, and optional error: GeocodingError. Outcomes are matched, no_results, low_confidence, error, and skipped; skip reasons are budget_exhausted, circuit_open, and unsupported_country.
All models expose to_dict(). Response serialization includes nested results/attempts and omits unavailable provider_response; attempt serialization omits unset skip/error fields. Frozen attributes do not make nested lists or dictionaries immutable.
Public literal types
| Type | Values |
|---|---|
Provider | primary, google, here |
FallbackTrigger | no_results, low_confidence, timeout, network, server_error |
FallbackReason | The triggers plus unsupported_country |
ErrorCode | http, network, timeout, invalid_response, provider_error, unsupported_country |
Autocomplete models
AutocompleteRequest requires q (1–256 nonblank characters) and a recognized country. Optional fields are near (Point), limit (1–10, default 5), exclude_sources, and session_token. The client generates a Google session token when omitted. AutocompleteResponse exposes suggestions, provider, fallback_reason, attempts, and optional provider_response; to_dict() serializes it. Each AutocompleteSuggestion has id, label, provider, and an optional session_token. Pass it to resolve_autocomplete to get one GeocodingResult. Both blocking and async clients support the same calls and a total timeout in seconds. See address autocomplete.
Resolution returns the address directly, without an envelope, attempt history, or raw provider response. It calls only the suggestion's provider and bypasses fallback budgets/circuit breakers. An empty primary lookup raises GeocodingError with code='provider_error'. Google/HERE must be configured on the resolving client. HTTP country is accepted only on primary autocomplete, while session_token remains SDK-only. These rules apply to both blocking and async clients.
GeocodingError
An Exception with message, provider, code, optional status, and attempts. to_dict() returns a serializable dictionary and omits status when absent. Terminal errors include the complete attempt history.
Caller deadline expiration raises TimeoutError; async cancellation raises asyncio.CancelledError. These stop the chain without triggering fallback. See errors.