Ir para o conteúdo

tempest_fastapi_sdk.integrations.places.google_places

Google Places API (New) v1: cliente assíncrono GooglePlacesClient sobre PlacesBackend, fábrica HTTP e parsers offline.

« Integrações e pagamentos


client

Async client and HTTP factory for the Google Places API (New) v1.

Implements :class:~tempest_fastapi_sdk.geo.PlacesBackend so services can swap between OpenStreetMap's :class:~tempest_fastapi_sdk.geo.OverpassPlacesBackend, :class:GooglePlacesClient and :class:~tempest_fastapi_sdk.testing.fakes.FakePlacesBackend without changing domain logic.

Nearby searches target POST /v1/places:searchNearby with a lean default X-Goog-FieldMask (keeping billing predictable) and normalize each result into :class:~tempest_fastapi_sdk.geo.PlaceSchema. Place Details and website lookups target GET /v1/places/{place_id}, reject path-traversal identifiers before sending network traffic, treat 404 as None, and surface other failures as :class:~tempest_fastapi_sdk.exceptions.GooglePlacesException.

DEFAULT_GOOGLE_PLACES_BASE_URL module-attribute

DEFAULT_GOOGLE_PLACES_BASE_URL: Final[str] = _DEFAULT_GOOGLE_PLACES_BASE_URL

Default root URL of the Google Places API (New) v1.

GOOGLE_PLACES_API_KEY_HEADER module-attribute

GOOGLE_PLACES_API_KEY_HEADER: Final[str] = 'X-Goog-Api-Key'

Header carrying the Google Cloud API key on every request.

GOOGLE_PLACES_FIELD_MASK_HEADER module-attribute

GOOGLE_PLACES_FIELD_MASK_HEADER: Final[str] = 'X-Goog-FieldMask'

Header naming the response fields requested from Places API (New) v1.

GOOGLE_PLACES_SOURCE module-attribute

GOOGLE_PLACES_SOURCE: Final[str] = 'google_places'

PlaceSchema.source value attached to normalized Google Places records.

MAX_NEARBY_RESULTS module-attribute

MAX_NEARBY_RESULTS: Final[int] = 20

Maximum maxResultCount accepted by POST /v1/places:searchNearby.

DEFAULT_NEARBY_FIELD_MASK module-attribute

DEFAULT_NEARBY_FIELD_MASK: Final[tuple[str, ...]] = (
    "places.id",
    "places.displayName",
    "places.formattedAddress",
    "places.location",
    "places.types",
    "places.rating",
    "places.internationalPhoneNumber",
    "places.websiteUri",
)

Default lean X-Goog-FieldMask for :meth:GooglePlacesClient.search_nearby.

DEFAULT_DETAILS_FIELD_MASK module-attribute

DEFAULT_DETAILS_FIELD_MASK: Final[tuple[str, ...]] = ("id", "displayName", "websiteUri")

Default X-Goog-FieldMask for :meth:GooglePlacesClient.get_place_details.

WEBSITE_FIELD_MASK module-attribute

WEBSITE_FIELD_MASK: Final[tuple[str, ...]] = ('websiteUri',)

Minimal X-Goog-FieldMask for :meth:GooglePlacesClient.get_place_website.

GooglePlacesClient

GooglePlacesClient(client: HTTPClient)

Async Google Places API (New) v1 client implementing :class:PlacesBackend.

Wraps an injected :class:~tempest_fastapi_sdk.utils.HTTPClient (typically built via :func:google_places_http_client), so the caller owns the connection pool lifecycle, retry policy and circuit breaker.

Satisfies :class:~tempest_fastapi_sdk.geo.PlacesBackend so domain services can switch between :class:~tempest_fastapi_sdk.geo.OverpassPlacesBackend, :class:GooglePlacesClient and :class:~tempest_fastapi_sdk.testing.fakes.FakePlacesBackend through a single protocol.

Initialize the Google Places client.

Parameters:

Name Type Description Default
client HTTPClient

Pre-configured HTTP client pointing at the Google Places API with X-Goog-Api-Key in its default headers (for example from :func:google_places_http_client).

required

search_nearby async

search_nearby(
    coordinate: Coordinate,
    *,
    radius_m: int = 800,
    included_types: Sequence[str] = (),
    max_results: int = MAX_NEARBY_RESULTS,
    field_mask: Sequence[str] = DEFAULT_NEARBY_FIELD_MASK,
) -> list[PlaceSchema]

Search POIs around coordinate via POST /v1/places:searchNearby.

Parameters:

Name Type Description Default
coordinate Coordinate

Center point of the circular search area.

required
radius_m int

Search radius in meters. Must be strictly positive. Defaults to 800.

800
included_types Sequence[str]

Optional Google Places Table A type filters (for example ("restaurant", "cafe")). Omitted from the request body when empty.

()
max_results int

Maximum number of results requested (maxResultCount). Must be between 1 and 20. Defaults to 20.

MAX_NEARBY_RESULTS
field_mask Sequence[str]

Non-empty sequence of Google Places field paths sent in X-Goog-FieldMask. Defaults to :data:DEFAULT_NEARBY_FIELD_MASK.

DEFAULT_NEARBY_FIELD_MASK

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Normalized places with source="google_places".

list[PlaceSchema]

Empty when Google Places returns no matches.

Raises:

Type Description
ValueError

When radius_m <= 0, max_results is outside 1..20, field_mask is empty/invalid, or included_types contains blank entries.

GooglePlacesException

When Google Places responds with a non-2xx status, a transport/circuit-breaker error occurs, or the response body is not a JSON object.

get_place_details async

get_place_details(
    place_id: str, *, field_mask: Sequence[str] = DEFAULT_DETAILS_FIELD_MASK
) -> PlaceSchema | None

Fetch details for a single place via GET /v1/places/{place_id}.

Parameters:

Name Type Description Default
place_id str

Google Place ID (single path segment, without the "places/" prefix). Empty values, /, \ and .. are rejected with ValueError before sending any request.

required
field_mask Sequence[str]

Non-empty sequence of Google Places field names sent in X-Goog-FieldMask. Defaults to :data:DEFAULT_DETAILS_FIELD_MASK (("id", "displayName", "websiteUri")).

DEFAULT_DETAILS_FIELD_MASK

Returns:

Type Description
PlaceSchema | None

PlaceSchema | None: Normalized place record, or None when

PlaceSchema | None

Google Places answers 404.

Raises:

Type Description
ValueError

When place_id or field_mask is invalid.

GooglePlacesException

When Google Places answers with a non-2xx status other than 404, a transport/circuit-breaker error occurs, or the response body is malformed.

get_place_website async

get_place_website(place_id: str) -> str | None

Fetch only the websiteUri of a place using a minimal field mask.

Issues GET /v1/places/{place_id} with X-Goog-FieldMask: websiteUri so billing stays restricted to the single requested field.

Parameters:

Name Type Description Default
place_id str

Google Place ID (single path segment, without the "places/" prefix). Empty values, /, \ and .. are rejected with ValueError.

required

Returns:

Type Description
str | None

str | None: Trimmed website URL when present, or None when the

str | None

place has no website or Google Places answers 404.

Raises:

Type Description
ValueError

When place_id is invalid.

GooglePlacesException

When Google Places answers with a non-2xx status other than 404, a transport/circuit-breaker error occurs, or the response body is malformed.

parse_google_place

parse_google_place(item: Mapping[str, JsonValue]) -> PlaceSchema | None

Parse one Google Places API (New) v1 Place into :class:PlaceSchema.

Items without an identifier (id or name starting with "places/") or without a non-empty displayName.text return None. Optional fields (such as location, formattedAddress, types, rating, internationalPhoneNumber and websiteUri) are populated when present and left as None / [] when omitted by the field mask.

Parameters:

Name Type Description Default
item Mapping[str, JsonValue]

Decoded JSON object representing one Google Places Place resource.

required

Returns:

Type Description
PlaceSchema | None

PlaceSchema | None: Normalized place with source="google_places",

PlaceSchema | None

or None when id or displayName is absent.

parse_google_places

parse_google_places(payload: Mapping[str, JsonValue]) -> list[PlaceSchema]

Parse a Google Places searchNearby payload into :class:PlaceSchema items.

Pure function with zero I/O, used by :meth:GooglePlacesClient.search_nearby and offline fixture tests. Entries missing an id or displayName are silently skipped; payloads without a places list return [].

Parameters:

Name Type Description Default
payload Mapping[str, JsonValue]

Decoded JSON body returned by POST /v1/places:searchNearby ({"places": [...]}).

required

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Normalized places with source="google_places".

list[PlaceSchema]

Empty when places is missing or empty.

google_places_http_client

google_places_http_client(
    api_key: str,
    *,
    base_url: str = DEFAULT_GOOGLE_PLACES_BASE_URL,
    timeout: float = 10.0,
    retry_policy: RetryPolicy | None = None,
    extra_headers: Mapping[str, str] | None = None,
    transport: AsyncBaseTransport | None = None,
) -> HTTPClient

Build an :class:HTTPClient configured for the Google Places API (New) v1.

Attaches api_key under the X-Goog-Api-Key default header (never in query parameters) and validates credentials and timeout up front.

Parameters:

Name Type Description Default
api_key str

Google Cloud API key with Places API (New) enabled. Blank strings are rejected with ValueError.

required
base_url str

Root URL of the Google Places API. Trailing slashes are stripped; blank strings are rejected with ValueError. Defaults to :data:DEFAULT_GOOGLE_PLACES_BASE_URL.

DEFAULT_GOOGLE_PLACES_BASE_URL
timeout float

Per-request timeout in seconds. Must be a positive finite number. Defaults to 10.0.

10.0
retry_policy RetryPolicy | None

Optional retry policy. None keeps the :class:HTTPClient default.

None
extra_headers Mapping[str, str] | None

Additional default headers merged on top of the authentication and Accept headers.

None
transport AsyncBaseTransport | None

Optional transport override (for example httpx.MockTransport in offline tests).

None

Returns:

Name Type Description
HTTPClient HTTPClient

Configured async HTTP client ready to pass to

HTTPClient

class:GooglePlacesClient.

Raises:

Type Description
ValueError

When api_key or base_url is empty/blank, or when timeout is not a positive finite number.