Skip to content

Google Maps scraper (gosom sidecar)

Need to discover local businesses and points of interest near a coordinate from Google Maps without paying per call for the Google Places API? The tempest_fastapi_sdk.integrations.places.gmaps_scraper module ships an async client for the gosom/google-maps-scraper sidecar with signature-level hardening, guaranteed job cleanup, and drop-in compatibility with the PlacesBackend protocol.

What comes out of the box:

  • GmapsScraperSettings and GmapsScraperHTTPKwargs — opt-in mixin (GMAPS_SCRAPER_ENABLED=False by default) with production URL validation and timing guards (GMAPS_SCRAPER_MAX_TIME_SECONDS >= 180).
  • gmaps_scraper_http_client — factory over HTTPClient that rejects a blank base_url.
  • GmapsScraperClient — creates the job (POST /api/v1/jobs), polls until "ok" or "failed", downloads and parses the CSV, and always issues DELETE /api/v1/jobs/{job_id} in finally. Implements PlacesBackend.
  • parse_gmaps_csv — pure csv.DictReader parser that deduplicates by place_id, normalizes Brazilian phone numbers (+55 DD ...), maps all 27 Brazilian states to their 2-letter UF, and tolerates malformed complete_address JSON.
  • GmapsScraperJobError — AppException (502, GMAPS_SCRAPER_JOB_ERROR, localized in pt-BR and en-US) raised on job failure or wait_seconds timeout.
  • FakeGmapsScraperClient — in-memory fake in tempest_fastapi_sdk.testing.fakes (and tempest_fastapi_sdk.testing) for tests without Docker or network access.

No extra dependency is required: httpx and csv are already available in the base SDK installation.

When to use it (and when not to)

Use this integration when you need an optional sidecar for local catalog enrichment (such as background discovery jobs) while keeping domain code isolated behind PlacesBackend.

Do not expose the sidecar on a public port or call it synchronously in a user-facing request: jobs take seconds to minutes and the SDK requires max_time >= 180s (the minimum the sidecar is expected to accept — not measured here). For fast, free lookups over open map data, prefer OverpassPlacesBackend.

Hardening the sidecar (Dockerfile and Docker Compose)

The gosom/google-maps-scraper sidecar needs outbound access to Google Maps. The container is expected (not measured here) to run without root privileges, a writable root filesystem, a host-exposed port, telemetry, Playwright browser downloads, or access to external IP-echo services — which is what the configuration below takes away from it.

What was and was not measured

No container was started to write this recipe. The sidecar's behavior — that it runs without root and with read_only: true, the effect of DISABLE_TELEMETRY and SCRAPEMATE_SKIP_PLAYWRIGHT_BROWSER_INSTALL, the IP-echo hosts it calls, the unauthenticated API and the refusal of a max_time below 3 minutes — was not verified; it is the expectation behind the configuration below. What the SDK guarantees (build_job, the DELETE in finally, the job_id and max_time_seconds validation) is covered by tests/integrations/places/test_gmaps_scraper.py. Before production, start the Compose service below and check one job end to end.

Hardened Dockerfile

Pin the upstream image by its sha256 digest instead of a moving :latest tag. Before upgrading, inspect the upstream manifest with docker buildx imagetools inspect ghcr.io/gosom/google-maps-scraper:latest and replace the digest below with the verified hash for your host architecture.

# Refresh the digest with:
# docker buildx imagetools inspect ghcr.io/gosom/google-maps-scraper:latest
FROM ghcr.io/gosom/google-maps-scraper@sha256:0000000000000000000000000000000000000000000000000000000000000000

ENV DISABLE_TELEMETRY=1 \
    SCRAPEMATE_SKIP_PLAYWRIGHT_BROWSER_INSTALL=1

USER 10001:10001

Hardened docker-compose.yaml service

Keep the service under profiles: ["gmaps"] so it only starts when explicitly requested (docker compose --profile gmaps up), omit ports: so it is reachable only on the internal Compose network, and point at 127.0.0.1, through extra_hosts, the IP-echo hosts the scraper is expected to call (not measured here).

services:
  gmaps-scraper:
    build:
      context: ./docker/gmaps-scraper
      dockerfile: Dockerfile
    profiles:
      - gmaps
    command:
      - "-web"
      - "-addr"
      - ":8080"
      - "-data-folder"
      - "/tmp/gmaps-data"
    environment:
      DISABLE_TELEMETRY: "1"
      SCRAPEMATE_SKIP_PLAYWRIGHT_BROWSER_INSTALL: "1"
    extra_hosts:
      - "api.ipify.org:127.0.0.1"
      - "ifconfig.me:127.0.0.1"
      - "icanhazip.com:127.0.0.1"
      - "ident.me:127.0.0.1"
      - "ifconfig.co:127.0.0.1"
    user: "10001:10001"
    read_only: true
    tmpfs:
      - /tmp:rw,noexec,nosuid,size=256m
    cap_drop:
      - ALL
    security_opt:
      - "no-new-privileges:true"
    cpus: 1.0
    mem_limit: 512m
    pids_limit: 128
    restart: unless-stopped

No ports: block in Compose

Not measured here: gosom/google-maps-scraper is expected to ship no authentication on /api/v1/jobs. In that case, publishing port 8080 on the host lets any reachable client submit arbitrary scraping jobs. Keep the sidecar reachable only through its internal service URL (http://gmaps-scraper:8080) on the private Compose network.

Configuration with GmapsScraperSettings

Compose GmapsScraperSettings with EnvironmentSettings and list BaseAppSettings last. Because the sidecar is optional, GMAPS_SCRAPER_ENABLED defaults to False: production boot only enforces a non-empty GMAPS_SCRAPER_URL when the flag is enabled.

from tempest_fastapi_sdk.geo import Coordinate, PlaceSchema
from tempest_fastapi_sdk.integrations.places.gmaps_scraper import (
    GmapsScraperClient,
    gmaps_scraper_http_client,
)
from tempest_fastapi_sdk.settings import (
    BaseAppSettings,
    EnvironmentSettings,
    GmapsScraperSettings,
)


class AppSettings(EnvironmentSettings, GmapsScraperSettings, BaseAppSettings):
    """Service settings with an opt-in Google Maps scraper sidecar."""


async def scrape_neighborhood(settings: AppSettings) -> list[PlaceSchema]:
    """Build the client from settings and run a keyword scraping job."""
    http = gmaps_scraper_http_client(**settings.gmaps_scraper_http_kwargs())
    client = GmapsScraperClient(
        http,
        default_keywords=("bakery", "pharmacy"),
        max_time_seconds=settings.GMAPS_SCRAPER_MAX_TIME_SECONDS,
        poll_seconds=settings.GMAPS_SCRAPER_POLL_SECONDS,
        wait_seconds=settings.GMAPS_SCRAPER_WAIT_SECONDS,
    )
    origin = Coordinate(latitude=-5.0892, longitude=-42.8019)
    try:
        return await client.scrape(
            origin,
            keywords=["padaria", "supermercado"],
            radius_m=800,
        )
    finally:
        await http.aclose()

Signature-level hardening in build_job

GmapsScraperClient.build_job always pins fast_mode=True and email=False, converts max_time_seconds to Go nanoseconds (max_time_seconds * 1_000_000_000), and intentionally omits fast_mode, email, and proxies parameters so callers cannot launch headless Chromium or route traffic through proxies by mistake.

from pydantic import JsonValue

from tempest_fastapi_sdk.geo import Coordinate
from tempest_fastapi_sdk.integrations.places.gmaps_scraper import GmapsScraperClient


def build_payload() -> dict[str, JsonValue]:
    """Build the hardened JSON body sent to POST /api/v1/jobs."""
    origin = Coordinate(latitude=-23.5505, longitude=-46.6333)
    return GmapsScraperClient.build_job(
        origin,
        keywords=["cafeteria"],
        radius_m=1000,
        max_time_seconds=180,
    )

Using it behind PlacesBackend

GmapsScraperClient satisfies the PlacesBackend protocol. When your service depends only on PlacesBackend, switching between OverpassPlacesBackend, GmapsScraperClient, and FakeGmapsScraperClient requires zero domain changes.

from tempest_fastapi_sdk.exceptions import GmapsScraperJobError
from tempest_fastapi_sdk.geo import Coordinate, PlacesBackend, PlaceSchema


async def discover_places(
    backend: PlacesBackend,
    origin: Coordinate,
) -> list[PlaceSchema]:
    """Query POIs through any PlacesBackend implementation."""
    try:
        return await backend.search_nearby(origin, radius_m=800)
    except GmapsScraperJobError:
        return []

In GmapsScraperClient.search_nearby(coordinate, radius_m=800, included_types=...), included_types overrides the search keywords for that call; when omitted, the client falls back to default_keywords. The SDK never hardcodes a domain category list — each service supplies the keywords relevant to its business.

Pure CSV parser (parse_gmaps_csv)

Use parse_gmaps_csv when you already have a CSV exported by a job (such as a fixture or saved snapshot) and want normalized PlaceSchema items with zero I/O.

from tempest_fastapi_sdk.geo import PlaceSchema
from tempest_fastapi_sdk.integrations.places.gmaps_scraper import parse_gmaps_csv


def normalize_snapshot(csv_text: str) -> list[PlaceSchema]:
    """Convert a sidecar CSV export into deduplicated PlaceSchema records."""
    return parse_gmaps_csv(csv_text)

The parser enforces these rules:

  • Deduplicates by place_id (first occurrence wins) and skips rows missing place_id, title, or a valid finite WGS84 coordinate.
  • Normalizes zero or empty review_rating values ("0", "0.0", "") to None.
  • Decodes complete_address via json.loads while tolerating malformed JSON, extracting borough, city, postal_code, and normalizing all 27 Brazilian states to 2-letter UFs (handling accents and "State of ..." prefixes).
  • Normalizes Brazilian phone numbers ("(86)99407-0266" → "+55 86 99407-0266") for Google Places API parity while leaving foreign numbers and 0800 numbers intact.

Offline testing with FakeGmapsScraperClient

Use FakeGmapsScraperClient to test code wired against GmapsScraperClient or PlacesBackend without starting Docker.

from tempest_fastapi_sdk.exceptions import GmapsScraperJobError
from tempest_fastapi_sdk.geo import Coordinate, PlaceSchema
from tempest_fastapi_sdk.testing.fakes import FakeGmapsScraperClient


async def test_service_offline() -> list[PlaceSchema]:
    """Exercise radius filtering and simulated failures without a sidecar."""
    fake = FakeGmapsScraperClient(default_keywords=("padaria",))
    origin = Coordinate(latitude=-5.0892, longitude=-42.8019)
    fake.add_place(
        PlaceSchema(
            source="gmaps_scraper",
            external_id="ChIJ-1",
            name="Padaria Central",
            coordinate=origin,
            phone="+55 86 99407-0266",
            state="PI",
        )
    )
    found = await fake.search_nearby(origin, radius_m=500)

    fake.fail_next(GmapsScraperJobError(job_id="job-1", status="failed"))
    try:
        await fake.scrape(origin, keywords=["padaria"])
    except GmapsScraperJobError:
        pass
    return found

Gotchas

  • Guaranteed cleanup in finally: GmapsScraperClient.scrape always calls DELETE /api/v1/jobs/{job_id}, even when the job finishes with "failed" or hits wait_seconds. If cleanup itself fails, it logs a WARNING without masking the original error.
  • Path-traversal guard on job_id: any id returned by the sidecar containing .., /, \, ?, #, %, or whitespace is rejected with ValueError before any follow-up path is built.
  • 180-second max_time floor: gosom/google-maps-scraper is expected (not measured here) to reject values below 3 minutes. The SDK refuses before calling the sidecar: build_job raises ValueError("max_time_seconds must be >= 180") and GmapsScraperSettings rejects a GMAPS_SCRAPER_MAX_TIME_SECONDS below 180 with ValidationError.

Recap

  • Run gosom/google-maps-scraper as an opt-in sidecar (profiles: ["gmaps"]), pinned by sha256 digest, with no ports:, non-root user, read_only: true, cap_drop: [ALL], and extra_hosts blocking external IP-echo services.
  • Compose GmapsScraperSettings (opt-in by default) and create the HTTP client with gmaps_scraper_http_client(**settings.gmaps_scraper_http_kwargs()).
  • Call GmapsScraperClient directly (scrape) or behind PlacesBackend (search_nearby), and test offline with FakeGmapsScraperClient.
  • See every signature in the integrations.places.gmaps_scraper API reference.