Skip to content

Places and POIs (Overpass and Google Places)

Need to list restaurants, pharmacies, bakeries or shops near a coordinate — either free of charge via OpenStreetMap or with commercial data from the Google Places API (New) v1? The SDK exposes one contract across both providers:

  • PlaceSchema — normalized point-of-interest schema with optional fields shared across providers (Overpass, Google Places, scrapers), plus raw_data preserving the provider payload.
  • PlacesBackend (and BoundingBoxPlacesBackend) — @runtime_checkable protocols that decouple your domain services from the concrete POI backend.
  • OverpassPlacesBackend (tempest_fastapi_sdk.geo) — async OpenStreetMap Overpass API client with radius search (search_nearby), bounding-box search (search_bbox), single element tag lookup (fetch_tags), strict validation against Overpass QL injection and exponential backoff retries.
  • GooglePlacesClient (tempest_fastapi_sdk.integrations.places.google_places) — async Google Places API (New) v1 client implementing the same PlacesBackend (search_nearby), plus get_place_details, get_place_website, the google_places_http_client factory, GooglePlacesSettings, and the offline parsers parse_google_places / parse_google_place.

No extra dependency is needed: httpx is already in the SDK's base install.

Radius search (search_nearby)

Use search_nearby when you have a center coordinate (such as a user's location) and want named shops and amenities within a radius in meters.

import httpx

from tempest_fastapi_sdk.geo import (
    Coordinate,
    OverpassPlacesBackend,
    PlaceSchema,
)


async def find_nearby() -> list[PlaceSchema]:
    """Fetch named POIs within 600 m of Praça da Sé."""
    origin = Coordinate(latitude=-23.5505, longitude=-46.6333)
    async with httpx.AsyncClient() as client:
        backend = OverpassPlacesBackend(
            user_agent="my-app/1.0 (https://my-app.example.com)",
            client=client,
        )
        return await backend.search_nearby(origin, radius_m=600, timeout_s=45)

If you omit client=, OverpassPlacesBackend creates and closes its own internal httpx.AsyncClient when used as an async context manager:

from tempest_fastapi_sdk.geo import (
    Coordinate,
    OverpassPlacesBackend,
    PlaceSchema,
)


async def find_with_owned_client() -> list[PlaceSchema]:
    """Let the backend manage the lifecycle of its internal HTTP client."""
    origin = Coordinate(latitude=-23.5505, longitude=-46.6333)
    async with OverpassPlacesBackend(
        user_agent="my-app/1.0 (https://my-app.example.com)",
    ) as backend:
        return await backend.search_nearby(origin, radius_m=800)

The generated Overpass QL queries node and way elements matching ["name"]["shop"] and ["name"]["amenity"~...] and finishes with out center;. For way elements, parse_overpass_places reads center.lat/center.lon automatically and drops unnamed elements.

Bounding-box search (search_bbox)

Use search_bbox to fetch an entire map viewport or neighborhood tile in a single request, minimizing calls against the public Overpass server.

import httpx

from tempest_fastapi_sdk.geo import (
    BoundingBox,
    OverpassPlacesBackend,
    PlaceSchema,
)


async def find_in_box() -> list[PlaceSchema]:
    """Fetch named POIs inside an axis-aligned bounding box."""
    box = BoundingBox(
        min_latitude=-23.56,
        max_latitude=-23.54,
        min_longitude=-46.65,
        max_longitude=-46.62,
    )
    async with httpx.AsyncClient() as client:
        backend = OverpassPlacesBackend(
            user_agent="my-app/1.0 (https://my-app.example.com)",
            client=client,
            amenity_types=("cafe", "restaurant", "pharmacy"),
        )
        return await backend.search_bbox(box, timeout_s=120)

BoundingBox is serialized in Overpass QL order (south, west, north, east) = (min_latitude, min_longitude, max_latitude, max_longitude). Pass amenity_types=() to query only shop elements.

Fetch tags for one element (fetch_tags)

Use fetch_tags when you already stored a place's external_id (such as "node/123456" or "way/789012") and want its full OpenStreetMap tags (opening_hours, cuisine, wheelchair, and so on).

import httpx

from tempest_fastapi_sdk.geo import OverpassPlacesBackend


async def load_place_tags(osm_id: str) -> dict[str, str]:
    """Fetch the raw OSM tag dictionary for a single element."""
    async with httpx.AsyncClient() as client:
        backend = OverpassPlacesBackend(
            user_agent="my-app/1.0 (https://my-app.example.com)",
            client=client,
        )
        return await backend.fetch_tags(osm_id, timeout_s=30)

osm_id must match node/<id>, way/<id> or relation/<id> with a positive ASCII integer id. Malformed strings and Overpass QL injection attempts raise ValueError before any network I/O. Every entry in amenity_types is likewise validated against ^[a-z0-9_]+$.

Pure parser (parse_overpass_places)

Use parse_overpass_places when you already hold a decoded Overpass JSON payload (from cache, disk or test fixtures) and want list[PlaceSchema] with no I/O.

from pydantic import JsonValue

from tempest_fastapi_sdk.geo import PlaceSchema, parse_overpass_places

payload: dict[str, JsonValue] = {
    "elements": [
        {
            "type": "way",
            "id": 987654,
            "center": {"lat": -23.5614, "lon": -46.6559},
            "tags": {
                "name": "Central Bakery",
                "shop": "bakery",
                "addr:street": "Av. Paulista",
                "addr:housenumber": "1000",
                "addr:suburb": "Bela Vista",
                "addr:city": "São Paulo",
                "addr:state": "SP",
                "addr:postcode": "01310-100",
                "contact:phone": "+55 11 3000-0000",
                "contact:website": "https://bakery.example.com",
            },
        }
    ]
}

places: list[PlaceSchema] = parse_overpass_places(payload)

Each PlaceSchema receives source="overpass", external_id=f"{type}/{id}", an address assembled from addr:street, addr:housenumber, addr:suburb (or addr:neighbourhood), addr:city, addr:state and addr:postcode, phone from phone/contact:phone, website from website/contact:website, categories from shop/amenity, and the full element in raw_data.

PlacesBackend protocol and testing with FakePlacesBackend

Type your services against PlacesBackend so the POI provider is swappable, and inject FakePlacesBackend in unit tests for offline Haversine radius and bounding-box filtering.

from tempest_fastapi_sdk.geo import Coordinate, PlacesBackend, PlaceSchema
from tempest_fastapi_sdk.testing.fakes import FakePlacesBackend


async def list_nearby_cafes(
    backend: PlacesBackend,
    center: Coordinate,
) -> list[str]:
    """Return names of cafes within 500 m of ``center``."""
    places: list[PlaceSchema] = await backend.search_nearby(center, radius_m=500)
    return [place.name for place in places if "cafe" in place.categories]


async def test_example() -> list[str]:
    """Exercise the service completely offline with FakePlacesBackend."""
    center = Coordinate(latitude=-23.5505, longitude=-46.6333)
    fake = FakePlacesBackend(
        [
            PlaceSchema(
                source="overpass",
                external_id="node/1",
                name="Square Coffee",
                coordinate=center,
                categories=["cafe"],
            )
        ]
    )
    return await list_nearby_cafes(fake, center)

FakePlacesBackend records nearby_queries, bbox_queries, tag_queries and calls, and supports add_place(...), add_tags(...) and fail_next(...).

Public Overpass limits and retries

The public endpoint at https://overpass-api.de/api/interpreter enforces usage policies that OverpassPlacesBackend guards by default:

Public instance usage policy

  • Explicit User-Agent required: measured on 2026-12-03 with one POST per agent to overpass-api.de/api/interpreter, public Overpass answered HTTP 406 with no User-Agent, with curl/8.0 and with python-httpx/0.28.1, and 200 for an agent that identifies the application. The constructor rejects blank, whitespace-only, curl and python-httpx agents with ValueError up front.
  • Rate limiting and transient overload (429, 502, 503, 504): by default the backend retries up to 3 times with exponential backoff via RetryPolicy. Supply a custom RetryPolicy or inject a configured HTTPClient with a circuit breaker.
  • Large areas: prefer search_bbox per tile or self-host Overpass for sustained high-volume workloads.
from tempest_fastapi_sdk.geo import (
    DEFAULT_OVERPASS_RETRY_STATUSES,
    OverpassPlacesBackend,
)
from tempest_fastapi_sdk.utils.retry import RetryPolicy

policy = RetryPolicy(
    max_attempts=4,
    backoff_initial_seconds=1.5,
    backoff_max_seconds=12.0,
    retry_statuses=DEFAULT_OVERPASS_RETRY_STATUSES,
)
backend = OverpassPlacesBackend(
    user_agent="my-app/1.0 (contact@my-app.example.com)",
    retry_policy=policy,
)

See the full API reference at tempest_fastapi_sdk.geo and tempest_fastapi_sdk.integrations.places.google_places.

Google Places API (New) v1 (GooglePlacesClient)

Use GooglePlacesClient when your service needs Google Places API (New) v1 data — such as ratings, international phone numbers and websiteUri — while keeping the exact same PlacesBackend protocol as OverpassPlacesBackend.

Configure with GooglePlacesSettings and google_places_http_client

Use GooglePlacesSettings to load GOOGLE_PLACES_API_KEY, GOOGLE_PLACES_BASE_URL, GOOGLE_PLACES_TIMEOUT and GOOGLE_PLACES_ENABLED, then splat **settings.google_places_http_kwargs() into google_places_http_client. The factory attaches the key via the X-Goog-Api-Key header (never in query parameters) and rejects empty credentials up front.

from tempest_fastapi_sdk.geo import Coordinate, PlacesBackend, PlaceSchema
from tempest_fastapi_sdk.integrations.places.google_places import (
    GooglePlacesClient,
    google_places_http_client,
)
from tempest_fastapi_sdk.settings import (
    BaseAppSettings,
    EnvironmentSettings,
    GooglePlacesSettings,
)


class AppSettings(GooglePlacesSettings, EnvironmentSettings, BaseAppSettings):
    """Application settings with production validation for Google Places."""


async def search_with_google_places(settings: AppSettings) -> list[PlaceSchema]:
    """Find nearby POIs with GooglePlacesClient behind PlacesBackend."""
    origin = Coordinate(latitude=-23.5505, longitude=-46.6333)
    async with google_places_http_client(
        **settings.google_places_http_kwargs()
    ) as http:
        client = GooglePlacesClient(http)
        backend: PlacesBackend = client
        return await backend.search_nearby(origin, radius_m=800)

In production (ENV=production), EnvironmentSettings fails boot when GOOGLE_PLACES_ENABLED=true and GOOGLE_PLACES_API_KEY is empty. Set GOOGLE_PLACES_ENABLED=false to ship before credentials are provisioned: the production check is skipped and "google_places" appears in settings.disabled_integrations().

Type filters, lean field_mask and details (get_place_details / get_place_website)

Pass included_types and max_results (1 to 20) to search_nearby to filter by Google Places Table A types. DEFAULT_NEARBY_FIELD_MASK requests only the fields PlaceSchema consumes (places.id, places.displayName, places.formattedAddress, places.location, places.types, places.rating, places.internationalPhoneNumber, places.websiteUri) so billing stays predictable.

Use get_place_details or get_place_website to look up a single place by place_id: both reject path-traversal values (/, \, ..) with ValueError, percent-encode the segment, and return None when Google answers 404.

from tempest_fastapi_sdk.exceptions import GooglePlacesException
from tempest_fastapi_sdk.geo import Coordinate, PlaceSchema
from tempest_fastapi_sdk.integrations.places.google_places import (
    GooglePlacesClient,
    google_places_http_client,
)


async def collect_nearby_websites(api_key: str) -> list[str]:
    """Find nearby pharmacies and resolve official websites via get_place_website."""
    origin = Coordinate(latitude=-23.5505, longitude=-46.6333)
    websites: list[str] = []
    async with google_places_http_client(api_key) as http:
        client = GooglePlacesClient(http)
        try:
            places: list[PlaceSchema] = await client.search_nearby(
                origin,
                radius_m=1000,
                included_types=("pharmacy",),
                max_results=10,
            )
            for place in places:
                site: str | None = place.website_uri or await client.get_place_website(
                    place.external_id
                )
                if site is not None:
                    websites.append(site)
        except GooglePlacesException as exc:
            raise RuntimeError(
                f"Google Places failed ({exc.upstream_status}): {exc.reason}"
            ) from exc
    return websites

Any non-2xx response other than 404 (or any transport/circuit-breaker failure) raises GooglePlacesException (status_code=502, code="GOOGLE_PLACES_ERROR", carrying upstream_status and reason in details with built-in PT-BR and EN-US translations).

Pure Google Places parser (parse_google_places and parse_google_place)

Use parse_google_places (for searchNearby payloads) or parse_google_place (for a single Place object) in offline tests or cached pipelines with zero network I/O:

from pydantic import JsonValue

from tempest_fastapi_sdk.geo import PlaceSchema
from tempest_fastapi_sdk.integrations.places.google_places import parse_google_places

google_payload: dict[str, JsonValue] = {
    "places": [
        {
            "id": "ChIJN1t_tDeuEmsRUsoyG83frY4",
            "displayName": {"text": "Avenue Coffee", "languageCode": "en"},
            "formattedAddress": "Av. Paulista, 1000 - São Paulo, SP",
            "location": {"latitude": -23.5614, "longitude": -46.6559},
            "types": ["cafe", "bakery"],
            "rating": 4.8,
            "internationalPhoneNumber": "+55 11 3000-0000",
            "websiteUri": "https://coffee.example.com",
        }
    ]
}

google_places: list[PlaceSchema] = parse_google_places(google_payload)

Recap

  • PlaceSchema normalizes POIs across providers with optional fields and raw_data.
  • PlacesBackend (and BoundingBoxPlacesBackend) decouples domain services from any specific places API so OverpassPlacesBackend, GooglePlacesClient and FakePlacesBackend are interchangeable.
  • OverpassPlacesBackend supports radius (search_nearby), bounding-box (search_bbox) and osm_id tag (fetch_tags) queries while enforcing an identifying user_agent and validating amenity_types and osm_id against Overpass QL injection.
  • GooglePlacesClient calls Google Places API (New) v1 via google_places_http_client and GooglePlacesSettings, sends lean X-Goog-FieldMask headers by default, guards place_id against path traversal and surfaces failures as GooglePlacesException.
  • FakePlacesBackend replaces the network in tests with real spatial filtering and fail_next failure steering.