# GET /get-scrape-results: retrieve Google Maps search results

> Retrieve LocalPipe Google Maps search results by webhook or by polling with pagination, including the per-keyword and per-location breakdown and every business field.
>
> Part of the LocalPipe API reference: https://www.localpipe.io/docs/maps-search-results (full reference in one file: https://www.localpipe.io/localpipe-api-docs.md, categories CSV: https://www.localpipe.io/localpipe-business-categories.csv)

## Retrieving Maps Search Results

### Option 1: Webhook (Recommended)

Include a `callback_url` in your request. When the search completes, results are POSTed to your URL:

```json
{
  "task_id": "uuid-here",
  "status": "success",
  "total_results": 476,
  "query": ["plumbers"],
  "locations": ["Austin, TX", "San Antonio, TX"],
  "data": [
    {
      "name": "Austin Plumbing Co",
      "phone": "+15125551234",
      "full_address": "123 Main St, Austin, TX 78701",
      "city": "Austin",
      "rating": 4.8,
      "review_count": 342,
      "website": "https://austinplumbing.com",
      "types": ["plumber", "contractor"],
      "matched_category": "Plumber",
      "price_level": "$20-30",
      "place_id": "ChIJ...",
      "business_id": "0x...",
      "latitude": 30.2672,
      "longitude": -97.7431,
      "is_claimed": true,
      "working_hours": { "Monday": "8AM-6PM", "Tuesday": "8AM-6PM" }
    }
  ]
}
```

### Option 2: Polling (with Pagination)

Poll for results using the `task_id`. Large result sets are paginated to stay within the 6 MB response limit.

```bash
# Check progress (or fetch first page if complete)
curl "https://uunrlffonnvmbsstkpze.supabase.co/functions/v1/get-scrape-results?task_id=uuid-here" \
  -H "apikey: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InV1bnJsZmZvbm52bWJzc3RrcHplIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzA0OTIwMzMsImV4cCI6MjA4NjA2ODAzM30.8Ic_U17YrZtsDVnYnIP0XJzrhZJOLDSlJ0AZfTS31FQ"

# Fetch a specific page
curl "https://uunrlffonnvmbsstkpze.supabase.co/functions/v1/get-scrape-results?task_id=uuid-here&limit=5000&offset=5000" \
  -H "apikey: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InV1bnJsZmZvbm52bWJzc3RrcHplIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzA0OTIwMzMsImV4cCI6MjA4NjA2ODAzM30.8Ic_U17YrZtsDVnYnIP0XJzrhZJOLDSlJ0AZfTS31FQ"
```

### Query Parameters

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| task_id | string | — | **Required.** The task ID returned by /maps-search. |
| limit | integer | 5000 | Page size. Max **5000**. |
| offset | integer | 0 | Number of leads to skip. |
| relevance_filter | string | off | Filter out off-topic results: `off` (default), `moderate`, or `strict`. Uses keyword stems against business types and names — useful when scraping broad terms like "consulting" that pull in unrelated categories. |

**Processing response:**
```json
{
  "task_id": "uuid-here",
  "status": "processing",
  "progress": {
    "completed_work_units": 15,
    "total_work_units": 45,
    "leads_found": 230,
    "target_limit": 500
  }
}
```

**Completed response (paginated):**
```json
{
  "task_id": "uuid-here",
  "status": "success",
  "total_results": 12450,
  "query": ["plumbers"],
  "locations": ["Texas"],
  "pagination": {
    "limit": 5000,
    "offset": 0,
    "next_offset": 5000,
    "has_more": true,
    "returned": 5000,
    "warning": "MORE LEADS AVAILABLE. Do NOT submit /enrich yet — fetch all pages first by re-calling this endpoint with offset=5000 until has_more=false."
  },
  "enrichment_contract": {
    "total_leads_to_enrich": 12450,
    "required_enrich_submissions": 12450,
    "instruction": "This scrape returned 12450 leads. You MUST submit exactly 12450 POST /enrich requests (one per lead) to enrich them all. Submitting fewer is a data loss bug — assert your enrich submission count == 12450 before declaring the workflow complete."
  },
  "data": [ ... ]
}
```

### Per-sub-query breakdown (batched jobs)

When a task was submitted with multiple keywords and/or locations **and** an integer `limit`, the response also includes:

Example: `query: ["dermatology clinic"]`, `location: ["Sydney, Australia", "Perth, Australia"]`, `limit: 300`. Each city starts with 150; Perth has no matches, so its whole share moves to Sydney, which returns the full 300.

```json
{
  "limit_scope": "per_keyword_location_pair",
  "per_pair_budget": 150,
  "sub_query_breakdown": {
    "by_location": [
      { "location": "Sydney, Australia", "found": 505, "returned": 300, "truncated": true },
      { "location": "Perth, Australia", "found": 0, "returned": 0, "truncated": false }
    ],
    "by_keyword": [
      { "keyword": "dermatology clinic", "found": 505, "returned": 300, "truncated": true }
    ]
  }
}
```

`limit` is one total budget for the job, split evenly across pairs (`per_pair_budget`), with any share a pair cannot use redistributed to pairs that still have more matches. Use `sub_query_breakdown` to tell **"this sub-query was truncated"** (`truncated: true` — raise `limit` or use Find ALL) apart from **"this sub-query genuinely had no matches"** (`found: 0`). You never need to split a batch into one call per keyword/city.


> **🚨 AI AGENTS / AUTOMATIONS — READ THIS.** The `enrichment_contract.required_enrich_submissions` field is the **ground-truth count** of `/enrich` calls you must submit. We see automations regularly scrape 5,000–20,000 leads then submit only 400–1,000 enrich requests because they processed one page and stopped. That is a silent data-loss bug and the user is paying for leads they never receive. Before declaring the workflow done: (1) paginate `/get-scrape-results` until `has_more=false`, accumulating every lead; (2) count what you accumulated and assert it equals `total_results`; (3) submit one `/enrich` per lead and assert your submission count equals `enrichment_contract.required_enrich_submissions`. If you exit early because of a shell timeout, resume from the last `offset` — do not skip leads.

**Pagination loop example:**
```javascript
let offset = 0;
const allLeads = [];
while (true) {
  const res = await fetch(
    `https://uunrlffonnvmbsstkpze.supabase.co/functions/v1/get-scrape-results?task_id=${taskId}&limit=5000&offset=${offset}`,
    { headers: { apikey: ANON_KEY } }
  );
  const page = await res.json();
  if (page.status !== "success") break; // still processing
  allLeads.push(...page.data);
  if (!page.pagination?.has_more) break;
  offset = page.pagination.next_offset;
}
```

> **Note on webhooks:** Webhook payloads always include the **full result set** in a single POST (no pagination). For very large jobs (>10,000 leads), prefer polling with pagination to avoid exceeding your endpoint's payload limit.

### Business Data Fields

Each business in the `data` array contains:

| Field | Type | Description |
|-------|------|-------------|
| name | string | Business name |
| phone | string | Phone number |
| full_address | string | Full street address |
| city | string | City name |
| rating | number | Google rating (1-5) |
| review_count | number | Number of Google reviews |
| website | string | Business website URL |
| types | string[] | Google business categories |
| matched_category | string | The exact category from Google's taxonomy that this business matched (null if no exact match) |
| price_level | string or null | Google's reported price range (e.g. $20-30 or $100+), legacy dollar marks, or null when unavailable |
| place_id | string | Google Maps Place ID |
| business_id | string | Google internal business ID (CID) |
| latitude | number | Latitude |
| longitude | number | Longitude |
| is_claimed | boolean | Whether the business has claimed its Google listing |
| working_hours | object | Operating hours by day |
