# LeadWebia API v1

> REST API to run Google Maps lead searches, read leads with phones, emails and website checks, manage them, and receive signed webhooks. Same account, credits and plans as the LeadWebia app.

- Docs (HTML): https://leadwebia.com/docs/api
- Base URL: `https://api.leadwebia.com/api/v1`
- Interactive reference: https://api.leadwebia.com/api/v1/docs
- OpenAPI: https://api.leadwebia.com/api/v1/openapi.json
- Auth: `Authorization: Bearer lw_live_...` (or `X-API-Key: lw_live_...`)

## Overview

JSON in and out, UTF-8. Field names in snake_case, timestamps in ISO 8601 UTC. The version is in the path (`/api/v1`); within v1 fields and endpoints are only added, never renamed or removed.

Every account can create API keys. Searches and reports use credits (1 credit = 1 business found); exports, integrations and webhooks need the credit pack or a paid plan, as in the app.

What you can build:

- Run Google Maps searches from your own app or script: niches, cities, "no website" or "with email" only.
- Pull every new lead into your CRM, database or sheet as it arrives, without missing or repeating one.
- Get a webhook the moment a lead has its emails, or when a search or prospect report is done.
- Check any website (CMS, SSL, speed, ads pixels) and find the emails it publishes.
- Create white-label prospect reports and AI outreach messages for the leads you want to pitch.
- Tag leads with your pipeline statuses, export them to CSV or push them to Google Sheets, Instantly or your webhook.

## Quickstart

The samples read the key from the `LEADWEBIA_API_KEY` environment variable.

### 1. Create an API key

Sign in at https://leadwebia.com, open the API page (https://leadwebia.com/api) and click "Create key". The full key (`lw_live_...`) is shown only once. Up to 5 active keys; revoke any of them at any time.

### 2. Check the key: GET /me

Free. Returns your plan and credits.

curl:

```bash
curl https://api.leadwebia.com/api/v1/me \
  -H "Authorization: Bearer $LEADWEBIA_API_KEY"
```

Python:

```python
import os
import requests

API = "https://api.leadwebia.com/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['LEADWEBIA_API_KEY']}"}

res = requests.get(f"{API}/me", headers=HEADERS, timeout=30)
res.raise_for_status()
print(res.json()["credits"])
```

JavaScript:

```javascript
const API = 'https://api.leadwebia.com/api/v1';
const headers = { Authorization: `Bearer ${process.env.LEADWEBIA_API_KEY}` };

const res = await fetch(`${API}/me`, { headers });
if (!res.ok) throw new Error((await res.json()).error.message);
const me = await res.json();
console.log(me.credits);
```

Response (abridged):

```json
{
  "email": "you@youragency.com",
  "plan": "pro",
  "credits": 4870,
  "report_cost": 20,
  "lead_statuses": [
    { "id": "6f1c…", "title": "New" },
    { "id": "a9d2…", "title": "Contacted" }
  ],
  "integrations": ["google_sheets"],
  "app_url": "https://leadwebia.com/home"
}
```

### 3. Find the area to search: GET /locations

Searches run on areas. `GET /locations` turns a city into its `area_id` (free). Pass `state` when several places share the name.

curl:

```bash
curl "https://api.leadwebia.com/api/v1/locations?city=Austin&country=US&state=Texas" \
  -H "Authorization: Bearer $LEADWEBIA_API_KEY"
```

Python:

```python
res = requests.get(
    f"{API}/locations",
    params={"city": "Austin", "country": "US", "state": "Texas"},
    headers=HEADERS,
    timeout=30,
)
res.raise_for_status()
area_id = res.json()["data"][0]["area_id"]
```

JavaScript:

```javascript
const params = new URLSearchParams({ city: 'Austin', country: 'US', state: 'Texas' });
const res = await fetch(`${API}/locations?${params}`, { headers });
const { data: areas } = await res.json();
const areaId = areas[0].area_id;
```

Response:

```json
{
  "data": [
    {
      "area_id": "US:TX:4671654",
      "name": "Austin",
      "state": "Texas",
      "country": "US",
      "population": 961855,
      "points": 64
    }
  ]
}
```

### 4. Start a search: POST /searches

Reserves `max_leads` credits and charges 1 per business delivered; unused credits come back. Always send an `Idempotency-Key`: a retry with the same key returns the same search instead of charging twice.

curl:

```bash
curl https://api.leadwebia.com/api/v1/searches \
  -H "Authorization: Bearer $LEADWEBIA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: austin-plumbers-2026-12-01" \
  -d '{
    "niches": ["plumber", "roofing contractor"],
    "area_ids": ["US:TX:4671654"],
    "max_leads": 200,
    "only_without_website": true
  }'
```

Python:

```python
import uuid

res = requests.post(
    f"{API}/searches",
    headers={**HEADERS, "Idempotency-Key": str(uuid.uuid4())},
    json={
        "niches": ["plumber", "roofing contractor"],
        "area_ids": [area_id],
        "max_leads": 200,
        "only_without_website": True,
    },
    timeout=30,
)
res.raise_for_status()
search = res.json()
print(search["search_id"], search["status"], search["credits_reserved"])
```

JavaScript:

```javascript
const res = await fetch(`${API}/searches`, {
  method: 'POST',
  headers: {
    ...headers,
    'Content-Type': 'application/json',
    'Idempotency-Key': crypto.randomUUID(),
  },
  body: JSON.stringify({
    niches: ['plumber', 'roofing contractor'],
    area_ids: [areaId],
    max_leads: 200,
    only_without_website: true,
  }),
});
const search = await res.json();
console.log(search.search_id, search.status, search.credits_reserved);
```

Response (abridged):

```json
{
  "search_id": "3b0e6c1e-…",
  "status": "queued",
  "niches": ["plumber", "roofing contractor"],
  "location": "Austin, Texas, US",
  "requested": 200,
  "delivered": 0,
  "credits_reserved": 200,
  "credits_charged": 0,
  "progress_pct": 0,
  "created_at": "2026-12-01T15:04:05Z",
  "app_url": "https://leadwebia.com/tasks/3b0e6c1e-…"
}
```

### 5. Get the leads

Poll `GET /leads?since=<cursor>` (oldest first; store `next_cursor` and pass it next time: no gaps, no repeats), or subscribe a webhook to `lead.created` (sent when the lead's email search is done).

curl:

```bash
# First call: start from the beginning (since=0) or from now (since=now)
curl "https://api.leadwebia.com/api/v1/leads?since=0&search_id=3b0e6c1e-…" \
  -H "Authorization: Bearer $LEADWEBIA_API_KEY"

# Next calls: pass the next_cursor of the previous answer
curl "https://api.leadwebia.com/api/v1/leads?since=eyJ0IjoiMjAyNi0xMi0wMVQxNTow…" \
  -H "Authorization: Bearer $LEADWEBIA_API_KEY"
```

Python:

```python
import time

cursor = "0"  # store it between runs (file, DB…)
while True:
    res = requests.get(
        f"{API}/leads",
        params={"since": cursor, "search_id": search["search_id"]},
        headers=HEADERS,
        timeout=30,
    )
    res.raise_for_status()
    page = res.json()
    for lead in page["data"]:
        print(lead["name"], lead["phone"], lead["emails"])
    cursor = page["next_cursor"]
    if not page["has_more"]:
        time.sleep(60)  # caught up: ask again in a minute
```

JavaScript:

```javascript
let cursor = '0'; // store it between runs (file, DB…)
for (;;) {
  const params = new URLSearchParams({ since: cursor, search_id: search.search_id });
  const res = await fetch(`${API}/leads?${params}`, { headers });
  const page = await res.json();
  for (const lead of page.data) console.log(lead.name, lead.phone, lead.emails);
  cursor = page.next_cursor;
  if (!page.has_more) await new Promise(r => setTimeout(r, 60_000));
}
```

Or subscribe a webhook:

curl:

```bash
curl https://api.leadwebia.com/api/v1/webhooks \
  -H "Authorization: Bearer $LEADWEBIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/hooks/leadwebia",
    "events": ["lead.created", "search.completed"],
    "description": "CRM sync"
  }'
```

Python:

```python
res = requests.post(
    f"{API}/webhooks",
    headers=HEADERS,
    json={
        "url": "https://example.com/hooks/leadwebia",
        "events": ["lead.created", "search.completed"],
        "description": "CRM sync",
    },
    timeout=30,
)
res.raise_for_status()
hook = res.json()
# Shown only once: keep it with your other secrets
signing_secret = hook["signing_secret"]
```

JavaScript:

```javascript
const res = await fetch(`${API}/webhooks`, {
  method: 'POST',
  headers: { ...headers, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    url: 'https://example.com/hooks/leadwebia',
    events: ['lead.created', 'search.completed'],
    description: 'CRM sync',
  }),
});
const hook = await res.json();
// Shown only once: keep it with your other secrets
const signingSecret = hook.signing_secret;
```

A lead (list fields):

```json
{
  "place_id": "ChIJ…",
  "name": "Lone Star Plumbing Co.",
  "category": "Plumber",
  "city": "Austin",
  "state": "Texas",
  "rating": 4.7,
  "user_ratings_total": 132,
  "website": null,
  "has_website": false,
  "phone": "+1 512-555-0142",
  "emails": ["office@lonestarplumbingco.com"],
  "status": "New",
  "cms": null,
  "cms_outdated": null,
  "niche": "plumber",
  "google_maps_url": "https://maps.google.com/?cid=…",
  "search_id": "3b0e6c1e-…",
  "saved_at": "2026-12-01T15:09:41Z"
}
```

## Authentication

```http
Authorization: Bearer lw_live_Ab3x…
# or
X-API-Key: lw_live_Ab3x…
```

- Keys are created and revoked only in the app (the API page), never through the API.
- A revoked key stops working on the very next request, and the webhooks created with it are disabled.
- Missing, malformed, unknown or revoked key: `401 invalid_api_key`.
- A key acts as your account and sees only your data. Keep it on a server, never in a browser or mobile app.

## Endpoints and credits

Paths are relative to the base URL. Credits are the same balance as in the app. Every parameter and response field is in the interactive reference (https://api.leadwebia.com/api/v1/docs).

### Account

| Endpoint | What it does | Credits |
|---|---|---|
| `GET /me` | Plan, credits left, pipeline statuses and connected integrations. Use it to test a key. | Free |
| `GET /lead-statuses` | Your pipeline statuses, in order. | Free |

### Locations

| Endpoint | What it does | Credits |
|---|---|---|
| `GET /locations` | Find the search areas (area_id) of a city: city, country (ISO code, e.g. US), optional state. | Free |

### Searches

| Endpoint | What it does | Credits |
|---|---|---|
| `POST /searches` | Start a search: 1–5 niches, 1–20 areas, max_leads 1–1,000, only_without_website, only_with_email, include_pagespeed, language (en or es). | Reserves max_leads, charges 1 per business delivered (with only_with_email: 1 per business with an email). Unused credits come back. |
| `GET /searches` | Your searches with their latest run. Filters: status, updated_since cursor. | Free |
| `GET /searches/{search_id}` | Status and progress of a search. | Free |
| `GET /searches/{search_id}/runs` | Every run of a search (the first one and each "more"). | Free |
| `POST /searches/{search_id}/more` | Load more businesses for the same search and area. | Same as starting a search. 409 search_exhausted when the area is used up. |
| `GET /searches/{search_id}/remaining` | Estimate of how many businesses are left in the area. | Free |

### Leads

| Endpoint | What it does | Credits |
|---|---|---|
| `GET /leads` | Your leads with filters (search_id, website, status, q, cms, cms_outdated, uses_ads, has_email), sort and offset pagination. | Free |
| `GET /leads?since={cursor}` | Feed of new leads, oldest first (saved over a minute ago). Store next_cursor and pass it next time. Only with search_id / q. | Free |
| `GET /leads/{place_id}` | Everything about one lead: contacts, socials, website checks, PageSpeed and Core Web Vitals. | Free |
| `PATCH /leads/{place_id}` | Set the pipeline status of a lead. | Free |
| `POST /leads/status` | Set the status of up to 500 leads, or of every lead of a search. | Free |
| `DELETE /leads/{place_id}` | Delete a lead (POST /leads/delete for up to 500). | Free (credits are not returned) |
| `POST /leads/{place_id}/outreach-message` | AI-written first message for that business. | Free · 300 a day (shared with the MCP) |

### Exports and integrations

| Endpoint | What it does | Credits |
|---|---|---|
| `POST /exports` | CSV of up to 5,000 leads (by place_ids or search_id). Returns a download URL. | Free · credit pack or paid plan |
| `GET /integrations` | Integrations you connected in the app. | Free |
| `GET /integrations/{kind}/targets` | Instantly campaigns or Google Sheets you can send to. | Free · credit pack or paid plan |
| `POST /integrations/{kind}/send` | Send leads to Instantly, Google Sheets or your webhook integration. | Free · credit pack or paid plan |
| `GET /integrations/sends/{task_id}` | Progress of a send. | Free |

### Prospect reports

| Endpoint | What it does | Credits |
|---|---|---|
| `POST /reports/lookup` | Find a business by name and city to report on. | Free · 10 a day |
| `POST /reports` | Create a prospect report for a place_id. | 20 when a new report runs; an existing one is returned free; refunded if it fails |
| `GET /reports/{place_id}` | Grade and summary (?full=true for the whole report). | Free |
| `POST /reports/{place_id}/share` | White-label link or PDF (GET /reports/{place_id}/pdf). | Free · credit pack or paid plan |

### Website tools

| Endpoint | What it does | Credits |
|---|---|---|
| `POST /tools/website-check` | CMS, technology, SSL, ads pixels and grade of any URL (include_pagespeed for speed). | Free |
| `POST /tools/emails` | Emails published on a website. | Free · 20 websites an hour |

### Webhooks

| Endpoint | What it does | Credits |
|---|---|---|
| `POST /webhooks` | Subscribe a URL to events. Returns signing_secret once. | Free · credit pack or paid plan |
| `GET /webhooks` | Your subscriptions (GET /webhooks/{id} for one). | Free |
| `PATCH /webhooks/{id}` | Change url, events, description or enabled. | Free |
| `DELETE /webhooks/{id}` | Unsubscribe. | Free |
| `POST /webhooks/{id}/test` | Send a signed ping now and see what your server answered. | Free |
| `GET /webhooks/{id}/deliveries` | Last 100 deliveries: event, status, attempts, time, error. | Free |

## Errors

Every non-2xx answer has this body; `X-Request-Id` is on every response.

```http
HTTP/1.1 402 Payment Required
X-Request-Id: req_8f3a…

{
  "error": {
    "code": "insufficient_credits",
    "message": "Not enough credits: 12 left, 50 needed.",
    "status": 402,
    "request_id": "req_8f3a…",
    "docs_url": "https://leadwebia.com/docs/api#errors"
  }
}
```

| Status | Codes | When |
|---|---|---|
| 401 | `invalid_api_key` | Missing, malformed, unknown or revoked key (same answer for all). |
| 402 | `insufficient_credits` | Not enough credits for the search or report. |
| 403 | `paid_plan_required`, `professional_plan_required` | The feature needs the credit pack or a paid plan (exports, integrations, webhooks, white-label sharing). |
| 404 | `not_found`, `search_not_found`, `lead_not_found`, `report_not_found` | It does not exist or belongs to another account. |
| 409 | `search_exhausted`, `legacy_search`, `idempotency_conflict`, `integration_not_connected`, `refresh_too_soon`, `report_not_ready` | The request is valid but can't be done now: the area is used up, the search is too old to continue, the Idempotency-Key was used with another body, the integration isn't connected, the report was refreshed recently or isn't ready yet. |
| 422 | `validation_error` | A parameter is missing or wrong. details lists each field. |
| 429 | `rate_limited`, `queue_full`, `message_limit`, `lookup_limit`, `email_lookup_limit` | Too many requests, or a daily/hourly cap. Wait for Retry-After seconds. |
| 500 | `internal_error` | Our fault. Retry later; send us the request_id if it keeps failing. |
| 502 | `upstream_error`, `website_unreadable` | A provider or the website you asked about didn't answer. |

Retry 429, 500 and 502 with backoff (honour `Retry-After`). Don't retry other 4xx answers unchanged.

## Pagination and cursors

Offset lists (`GET /leads`, `GET /searches`): `limit` (1-100, default 25) and `offset`.

```http
GET /leads?website=without_website&limit=25&offset=50

{
  "data": [ … ],
  "total": 412,
  "offset": 50,
  "next_offset": 75,
  "has_more": true
}
```

Cursor feeds (`GET /leads?since=`, `GET /searches?updated_since=`): oldest first, opaque `next_cursor`; store it and send it back. Never misses or repeats an item.

- `since=0` (or empty) starts from the first lead; `since=now` from the current end.
- The lead feed combines only with `search_id` and `q` (emails, website checks and CRM status arrive after a lead is saved: filter on your side or use the `lead.created` webhook).
- Feeds list items older than one minute, so a write still in progress is never skipped.
- `has_more: true`: call again right away; `false`: caught up, wait a minute or two.

```http
GET /leads?since=eyJ0IjoiMjAyNi0xMi0wMVQxNTow…

{
  "data": [ … ],
  "next_cursor": "eyJ0IjoiMjAyNi0xMi0wMVQxNToxM…",
  "has_more": false
}
```

Single objects are returned bare, without a `data` wrapper.

## Idempotency

`POST /searches` and `POST /searches/{search_id}/more` accept `Idempotency-Key` (1-255 characters, e.g. a UUID).

- Same key, same body: the same search is returned and credits are reserved once.
- Same key, different body: `409 idempotency_conflict`.
- No header: every POST starts a new search.
- `POST /reports` needs no key: an existing or running report is returned without a new charge.

## Rate limits

- 60 requests a minute per key; 120 a minute per account (all keys).
- Credit-spending calls (start a search, load more, create a report): 10 a minute per account.
- Existing caps: 300 AI outreach messages a day, 20 email lookups an hour, 10 business lookups a day, and the searches that can run at once on your plan.
- Headers on every answer: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`. Over a limit: `429 rate_limited` (or the cap's code) with `Retry-After` in seconds.

## Webhooks

Subscribe a URL with `POST /webhooks`; events cover all your searches. The answer includes `signing_secret`, shown only once. Up to 10 webhooks per account, HTTPS only; credit pack or paid plan. Separate from the app's webhook integration (https://leadwebia.com/integrations/webhooks).

### Events

| Event | When | data |
|---|---|---|
| `lead.created` | Once per lead, when its email search is done (so emails and socials are in). | The lead, same shape as GET /leads/{place_id} |
| `search.completed` | A search run finished, including "area used up". | The search, same shape as GET /searches/{search_id} |
| `search.failed` | A search run failed. Unused credits are already back. | The search |
| `report.ready` | A prospect report is ready. | place_id, grade, score, app_url (full report: GET /reports/{place_id}) |
| `report.failed` | A prospect report failed. Its credits are refunded. | place_id, error |
| `ping` | Only when you call POST /webhooks/{id}/test. | Empty object |

### Payload

One event per request:

```http
POST /hooks/leadwebia HTTP/1.1
Content-Type: application/json
X-LeadWebia-Event: lead.created
X-LeadWebia-Delivery: evt_5c1f…
X-LeadWebia-Timestamp: 1764601781
X-LeadWebia-Signature: sha256=9b1d0c…

{
  "id": "evt_5c1f…",
  "type": "lead.created",
  "created_at": "2026-12-01T15:09:41Z",
  "api_version": "v1",
  "data": { "place_id": "ChIJ…", "name": "Lone Star Plumbing Co.", … }
}
```

### Verify signatures

`X-LeadWebia-Signature` is `sha256=` plus the hex HMAC-SHA256 of the raw request body, keyed with the webhook's signing secret. Compute it over the exact bytes received, compare in constant time, then dedupe by event `id`.

Python:

```python
# Flask: request.get_data() is the raw body the signature covers.
import hashlib
import hmac
import os

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["LEADWEBIA_SIGNING_SECRET"].encode()
seen = set()  # use your database in production


@app.post("/hooks/leadwebia")
def leadwebia():
    raw = request.get_data()
    expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-LeadWebia-Signature", "")):
        abort(401)

    event = request.get_json()
    if event["id"] in seen:  # a retry of an event you already handled
        return "", 200
    seen.add(event["id"])

    if event["type"] == "lead.created":
        lead = event["data"]
        # lead["place_id"], lead["name"], lead["phone"], lead["emails"]…
    return "", 200
```

Node.js:

```javascript
// Express: keep the raw body, the signature is computed over its exact bytes.
const crypto = require('crypto');
const express = require('express');
const app = express();
const seen = new Set(); // use your database in production

app.post('/hooks/leadwebia', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.get('X-LeadWebia-Signature') || '';
  const expected = 'sha256=' + crypto
    .createHmac('sha256', process.env.LEADWEBIA_SIGNING_SECRET)
    .update(req.body)                       // Buffer with the raw body
    .digest('hex');
  const valid = header.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected));
  if (!valid) return res.sendStatus(401);

  const event = JSON.parse(req.body.toString('utf8'));
  if (seen.has(event.id)) return res.sendStatus(200); // a retry you already handled
  seen.add(event.id);

  if (event.type === 'lead.created') {
    const lead = event.data;
    // lead.place_id, lead.name, lead.phone, lead.emails…
  }
  res.sendStatus(200);
});
```

### Retries and 410

- Answer any 2xx quickly; anything else (or no answer) is a failure.
- Retried 3 times right away, then after 1 minute, 10 minutes and 1 hour. Retries carry the same event id.
- A lead is never sent twice to the same webhook as a new event.
- Answer `410 Gone` to delete the subscription (REST hooks convention).
- 50 failed events in a row disable the webhook (`GET /webhooks` shows why); re-enable with `PATCH /webhooks/{id}` and `enabled: true`.
- `POST /webhooks/{id}/test` sends a signed `ping`; `GET /webhooks/{id}/deliveries` lists the last 100 deliveries.

## Zapier, Make and n8n

- Instant triggers (REST hooks): on subscribe POST the tool's webhook URL to `/webhooks`; on unsubscribe `DELETE /webhooks/{id}`. A `410` from the tool removes it too.
- Polling triggers: `GET /leads?since=` on a schedule, keep `next_cursor` in the tool's storage.
- Actions: HTTP request step with the `Authorization` header.
- No code: the app's webhook integration sends a search's leads to a Zapier, Make or n8n URL without an API key.

## Changelog

- v1 (2026-12): First public version: account, locations, searches, leads (with the since feed), exports, integrations, prospect reports, website tools and webhooks.
