> ## Documentation Index
> Fetch the complete documentation index at: https://docs.scrapebadger.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Ask Perplexity

> Send a prompt to the real perplexity.ai and get the grounded answer as structured JSON, with its cited sources, search queries and related questions.

Ask **the real `perplexity.ai`** a question anonymously and get the answer back
as JSON, plus every source Perplexity retrieved, which of those it cited, and
the sub-queries it searched for.

Accepts `GET` (query params) or `POST` (JSON body) with identical fields.

**Credits:** 20

> [!WARNING]
>
> A call can take up to about 75 s while exits are tried, so set your client
> timeout to at least 90 s. Every call renders a fresh answer: nothing is
> cached, so the same prompt sent again gets a new answer and is billed again.
> At volume, run asks [asynchronously](#ask-at-volume).

## Authorization

**X-API-Key** `string` *required*

Your ScrapeBadger API key.

## Query Parameters

**prompt** `string` *required*

The question to ask. Maximum **4,096 characters**. Each request is standalone,
so include all the context you need here.

**country** `string`

ISO-3166 alpha-2 market, e.g. `US`, `DE`, `JP`. Sets the ask's language and
timezone (e.g. `DE`: `de-DE`, `Europe/Berlin`). Omit it and the market whose
exits answer best right now is used.

The egress is **best-effort**: when that market has no exit left, another one
carries the ask and the response `country` says which. Set `strict_country`
to forbid that.

**strict\_country** `boolean` (default: false)

Answer only from an exit in `country`, never another one. When no exit there
answers in time the call fails with **`503`** and
`detail.code = "country_unavailable"`. It is **not billed** (only `2xx`
responses are). Requires `country` — `400` otherwise. A JSON `boolean` on
`POST`.

**location** `string`

Where the asker is. Perplexity answers a local question (`best dentist`,
`popular cafes`, `moving companies`) for this place. Without it, that place
is the exit's city, which changes from call to call (a `JP` exit can be in
Hamamatsu one call and Atsugi the next).

A city from the list below, or `lat,lng` in decimal degrees (up to 8 decimal
places), e.g. `35.6812,139.7671`. Case does not matter, and spaces and
underscores count as hyphens: `New York` and `new_york` both mean
`new-york`. Any other value is a **`400`**, not billed. A JSON `string` on
`POST`.

It does not change the egress. `country` still picks the exit and the answer
language, so pair the two: `country=JP&location=tokyo`. Questions that are
not local are unaffected.

**Cities**

* **Japan:** `tokyo`, `yokohama`, `osaka`, `nagoya`, `sapporo`, `fukuoka`, `kyoto`, `kobe`, `sendai`, `hiroshima`
* **Asia-Pacific:** `seoul`, `busan`, `taipei`, `hong-kong`, `singapore`, `bangkok`, `hanoi`, `ho-chi-minh-city`, `jakarta`, `kuala-lumpur`, `manila`, `mumbai`, `delhi`, `bangalore`, `sydney`, `melbourne`
* **Americas:** `new-york`, `los-angeles`, `chicago`, `san-francisco`, `houston`, `miami`, `seattle`, `washington`, `toronto`, `vancouver`, `mexico-city`, `sao-paulo`, `buenos-aires`
* **Europe:** `london`, `manchester`, `paris`, `berlin`, `munich`, `hamburg`, `frankfurt`, `madrid`, `barcelona`, `rome`, `milan`, `amsterdam`, `brussels`, `vienna`, `zurich`, `lisbon`, `warsaw`, `istanbul`

**focus** `string` (default: web)

Retrieval focus: `web`, `scholar` (academic sources) or `social`
(discussions and forums).

**html** `boolean` (default: false)

Also return `answer_html`: the answer rendered as an HTML fragment, with each
`[n]` citation linked to its source. See [Answer HTML](#answer-html). Same price.

**raw** `boolean` (default: false)

Also return `raw`: Perplexity's own answer object, exactly as it sent it. See
[Raw response](#raw-response). Same price.

## Response

**prompt** `string`

Echo of the prompt you sent.

**answer** `string`

The answer text. Citation offsets index into this string.

**answer\_markdown** `string | null`

The answer with its Markdown formatting.

**citations** `Citation[]`

The sources the answer actually references.

**Citation**

**url** `string`

Source URL.

**title** `string | null`

Page title.

**snippet** `string | null`

Snippet Perplexity retrieved from the page.

**domain** `string | null`

Hostname, e.g. `techcrunch.com`.

**source\_type** `string | null`

Perplexity's source kind, e.g. `web`, `scholar`, `social`.

**pub\_date\_utc** `number | null`

Publication date as a Unix timestamp.

**published\_at** `string | null`

Publication date as an ISO-8601 UTC string.

**last\_updated** `string | null`

Last-updated date as reported by Perplexity.

**ref\_index** `integer | null`

The inline `[n]` marker number.

**start\_index** `integer | null`

Character offset in `answer` where the cited span begins.

**end\_index** `integer | null`

Character offset in `answer` where the cited span ends.

**matched\_text** `string | null`

The substring of `answer` this source supports.

**search\_results** `SearchResult[]`

The **full** set Perplexity retrieved, cited or not. Same fields as
`Citation` without the answer offsets, plus `cited` (`boolean`).

**source\_domains** `string[]`

Distinct hostnames across the sources.

**related\_questions** `string[]`

Perplexity's suggested follow-up questions.

**images** `MediaItem[]`

Images attached to the answer (`url`, `title`, `source_url`, `thumbnail`).

**videos** `MediaItem[]`

Videos attached to the answer, same shape.

**web\_search\_triggered** `boolean`

Whether Perplexity searched the web for this answer.

**truncated** `boolean`

`true` when the stream budget expired mid-answer, so `answer` is partial.

**search\_queries** `string[]`

The sub-queries Perplexity sent to its search backend (its retrieval fan-out).

**search\_query\_str** `string`

The phrase this answer's web search ran under. For a prompt of up to 35 characters it is the prompt itself. For a longer prompt it is usually a shorter phrase made of the prompt's own key words. See [What was searched](#what-was-searched).

**whole\_prompt** `boolean`

`true` when the search ran under your whole prompt, `false` when it ran under the shorter `search_query_str`. The answer is written for your whole prompt either way.

**focus** `string`

The retrieval focus used.

**model** `string | null`

Which model answered. Reported, not requestable.

**backend\_uuid** `string | null`

Perplexity's id for this answer.

**country** `string`

The market that actually answered. Without `strict_country` it can differ from the `country` you asked for.

**location** `string | null`

The `location` the ask was sent with, in canonical form, e.g. `tokyo` or `35.6812,139.7671`. `null` when you did not set one.

**answer\_length** `integer`

Length of `answer` in characters.

**citation\_count** `integer`

Number of entries in `citations`.

**latency\_ms** `integer`

End-to-end time in milliseconds.

**created\_utc** `number | null`

Answer creation time as a Unix timestamp.

**created\_at** `string | null`

Answer creation time as an ISO-8601 UTC string.

**answer\_html** `string`

Only with `html=true`. The answer as an HTML fragment. See [Answer HTML](#answer-html).

**raw** `object | null`

Only with `raw=true`. Perplexity's final answer object as received. See [Raw response](#raw-response).

## Example

```bash cURL theme={null}
curl -G "https://scrapebadger.com/v1/perplexity/ask" \
  -H "X-API-Key: YOUR_API_KEY" \
  --data-urlencode "prompt=Which companies lead the web scraping API market?" \
  --data-urlencode "country=US" \
  --max-time 120
```

```javascript Node.js theme={null}
const res = await fetch("https://scrapebadger.com/v1/perplexity/ask", {
  method: "POST",
  headers: {
    "X-API-Key": process.env.SCRAPEBADGER_API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    prompt: "Which companies lead the web scraping API market?",
    country: "US",
  }),
  signal: AbortSignal.timeout(120_000),
});
const data = await res.json();
console.log(data.country, data.answer);
```

```python Python theme={null}
import requests

res = requests.post(
    "https://scrapebadger.com/v1/perplexity/ask",
    headers={"X-API-Key": "YOUR_API_KEY"},
    json={"prompt": "Which companies lead the web scraping API market?", "country": "US"},
    timeout=120,
)
data = res.json()
for c in data["citations"]:
    print(c["domain"], "->", c["matched_text"])
```

## What was searched

Perplexity's anonymous tier limits how long a search phrase can be. A prompt of
up to 35 characters is searched exactly as you wrote it. A longer prompt is
still answered in full, but its web search usually runs under a shorter phrase
made of the prompt's own key words:

| Prompt | `search_query_str` |
| - | - |
| `Best CRM for a small agency?` | `Best CRM for a small agency?` |
| `What are the best CRM tools for small businesses in the US?` | `CRM tools small businesses US` |
| `Welche Steuerberater in München sind auf Start-ups und junge GmbHs spezialisiert?` | `Steuerberater München Start-ups` |

Every response tells you which case you got. `search_query_str` is the phrase
that was searched, and `whole_prompt` is `true` when that phrase was your whole
prompt:

```json theme={null}
{
  "search_query_str": "CRM tools small businesses US",
  "whole_prompt": false
}
```

Log both fields when you compare answers over time: two answers to the same
prompt are only comparable search for search when their `search_query_str`
matches.

The phrase is built from the nouns, names and acronyms of your prompt, earlier
words first. Question words and words such as `best`, `which` or `recommend`
never enter it. To steer the search of a long prompt, name the topic with
specific nouns near the start.

## Strict country

By default `country` is best-effort, so a market that is short of exits still
gets an answer, from another market. Check the response `country` to see which
one answered. When the market matters more than the answer (local rankings,
per-country visibility tracking), set `strict_country=true`:

```bash theme={null}
curl -G "https://scrapebadger.com/v1/perplexity/ask" \
  -H "X-API-Key: YOUR_API_KEY" \
  --data-urlencode "prompt=best electricity provider" \
  --data-urlencode "country=DE" \
  --data-urlencode "strict_country=true" \
  --max-time 120
```

If no exit in that market answers in time you get a `503`, which is not billed.
Retry later rather than dropping `strict_country`:

```json 503 Response theme={null}
{
  "detail": {
    "code": "country_unavailable",
    "message": "no DE exit answered in 16 attempts {...}; strict_country never falls back to another country"
  }
}
```

## Location

A question that names no place, such as `best dentist`, gets an answer for the
asker's city. Without `location`, that is the exit's city, so it changes
between calls. Set `location` to keep those answers on one place:

```bash theme={null}
curl -G "https://scrapebadger.com/v1/perplexity/ask" \
  -H "X-API-Key: YOUR_API_KEY" \
  --data-urlencode "prompt=best dentist" \
  --data-urlencode "country=JP" \
  --data-urlencode "location=tokyo" \
  --max-time 120
```

Perplexity now answers for Tokyo. The response carries the value next to
`country`:

```json theme={null}
{
  "country": "JP",
  "location": "tokyo"
}
```

An unknown city or a malformed `lat,lng` fails before any attempt is made. It
is not billed:

```json 400 Response theme={null}
{
  "detail": "location must be a city (tokyo, osaka, seoul, new-york, london, ...) or 'lat,lng' in decimal degrees"
}
```

## Answer HTML

Perplexity has no server-side HTML for an answer. Its website builds the answer
page in the browser from a JSON stream, and that stream is what we read. With
`html=true` we render the answer's Markdown as HTML for you:

* **Formatting:** headings, paragraphs, bold and italics, lists, tables, code
  and links, as Perplexity wrote them.
* **Citations:** each `[n]` marker becomes a link to its source:
  `<a class="citation" data-ref="n" href="https://source.example/page">[n]</a>`.
  `data-ref` matches `ref_index` in `citations`.
* **Safe to embed:** raw HTML inside the answer is dropped, and so are
  `javascript:` and `data:` links.
* **A fragment, not a page:** no `<html>` or `<body>` and no styles. Wrap it in
  your own page and style `a.citation` as you like.

```html theme={null}
<h2>Tallest buildings in Vilnius</h2>
<p>The <strong>Europa Tower</strong> is 148 m tall<a class="citation" data-ref="1" href="https://en.wikipedia.org/wiki/Europa_Tower" title="Europa Tower - Wikipedia" target="_blank" rel="noopener nofollow">[1]</a>.</p>
```

## Raw response

With `raw=true` the response also carries `raw`: Perplexity's final answer
object exactly as its app API sent it. Every other field in the response is
parsed from it. It includes the answer `blocks` (Markdown, web results, the
search fan-out), `related_queries`, `display_model`, `mode`, `thread_url_slug`
and `status`. Field names and shapes are Perplexity's and can change without
notice, so prefer the parsed fields when they cover what you need. The thread's
write token (`read_write_token`) is removed. It adds about 100 KB to the response, so ask for it only when you need it.

## Run this asynchronously

Calls on this API can run in the background, so you don't hold a connection open while they work. Add one of these to the call:

| Add | What you get |
| - | - |
| `async=true` | The normal response if the call finishes within 25 s. Otherwise `202` with a `request_id`, which you poll at `GET /v1/requests/{request_id}` for free. |
| `callback_url=https://…` | `202` at once. When the call completes, the result is POSTed to your URL, signed with your webhook secret. |
| `Idempotency-Key: <your id>` header | A resent submit returns the first call instead of running it again. |

```bash theme={null} theme={null} theme={null}
curl -s "https://scrapebadger.com/v1/...?your=params&async=true" \
  -H "X-API-Key: $SCRAPEBADGER_API_KEY"
# 202 {"request_id": "…", "status": "running", …}, then:
curl -s "https://scrapebadger.com/v1/requests/REQUEST_ID" \
  -H "X-API-Key: $SCRAPEBADGER_API_KEY"
```

An async call is billed once, when it completes. See [Async requests and webhooks](https://docs.scrapebadger.com/long-running-requests.md) for webhooks, signatures and the SDK helpers.

## Ask at volume

To run thousands of asks, don't hold a connection open for each one. Submit
every ask with a callback and an idempotency key. Each submit returns `202` at
once, and each answer arrives at your server as a signed webhook.

1. **Submit** each ask with `X-Callback-URL` (or `callback_url`) and an
   `Idempotency-Key` made from your own job id. Store the `request_id` you get
   back with the job.
2. **Verify** each delivery's `X-ScrapeBadger-Signature` with your
   [webhook secret](https://docs.scrapebadger.com/long-running-requests.md#your-webhook-secret).
3. **Deduplicate** on `request_id`. Deliveries are at least once, so the same
   answer can arrive twice.
4. **Resubmit `5xx` failures with a new key.** A failed ask is not billed. Its
   old key would only replay the same failure. Don't resubmit a `4xx`: fix the
   request instead.

### Submit

Resending a submit with the same key, after a timeout or a network error, is
safe: you get the first ask's `202` back with `Idempotent-Replayed: true`, and
nothing is billed twice. A `429` on submit is not billed either; resend it later
with the same key.

```bash cURL theme={null}
curl -s "https://scrapebadger.com/v1/perplexity/ask?async_wait=0" \
  -H "X-API-Key: $SCRAPEBADGER_API_KEY" \
  -H "Idempotency-Key: job-4815-try-1" \
  -H "X-Callback-URL: https://hooks.example.com/scrapebadger" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Which companies lead the web scraping API market?", "country": "US"}'
```

```python Python SDK theme={null}
import asyncio
from scrapebadger import ScrapeBadger

HOOK = "https://hooks.example.com/scrapebadger"
jobs = [("job-4815", "Which companies lead the web scraping API market?")]


async def submit(client, job_id: str, prompt: str, attempt: int = 1) -> str:
    req = await client.requests.submit(
        "/v1/perplexity/ask",
        method="POST",
        json={"prompt": prompt, "country": "US"},
        callback_url=HOOK,
        idempotency_key=f"{job_id}-try-{attempt}",
        wait=0,
    )
    return req.request_id  # store it with the job to match the webhook


async def main():
    async with ScrapeBadger(api_key="YOUR_API_KEY") as client:
        for job_id, prompt in jobs:
            print(job_id, await submit(client, job_id, prompt))

asyncio.run(main())
```

```typescript Node SDK theme={null}
import { ScrapeBadger } from "scrapebadger";

const client = new ScrapeBadger({ apiKey: process.env.SCRAPEBADGER_API_KEY });

async function submit(jobId: string, prompt: string, attempt = 1): Promise<string> {
  const req = await client.requests.submit("/v1/perplexity/ask", {
    method: "POST",
    body: { prompt, country: "US" },
    callbackUrl: "https://hooks.example.com/scrapebadger",
    idempotencyKey: `${jobId}-try-${attempt}`,
    wait: 0,
  });
  return req.requestId; // store it with the job to match the webhook
}
```

> [!NOTE]
>
> **Keep `async_wait` at 0.** A callback already means `async_wait=0` unless
> you set a wait, and the webhook is sent either way. A wait only delays the
> `202`. At volume it costs you an open connection per ask for up to that many
> seconds, so Perplexity's answer time, not your
> [rate limit](https://docs.scrapebadger.com/rate-limits.md), sets how fast you can submit.

### Receive

The receiver checks the signature, skips repeats and answers before it does any
work. A `2xx` within 10 s counts as delivered. Anything slower is sent again.

```python Python (FastAPI) theme={null}
import json
import os

import redis
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
from scrapebadger.webhooks import verify_signature

app = FastAPI()
SECRET = os.environ["SCRAPEBADGER_WEBHOOK_SECRET"]
r = redis.Redis()


def first_time(request_id: str) -> bool:
    return bool(r.set(f"sb:seen:{request_id}", 1, nx=True, ex=86400))


@app.post("/hooks/scrapebadger")
async def perplexity_hook(request: Request, background: BackgroundTasks):
    raw = await request.body()  # the exact bytes that were signed
    try:
        event = json.loads(raw)
    except ValueError:
        raise HTTPException(status_code=400)
    signature = request.headers.get("X-ScrapeBadger-Signature", "")
    if not verify_signature(SECRET, raw, signature, sent_at=event.get("sent_at")):
        raise HTTPException(status_code=401)
    if first_time(event["request_id"]):
        background.add_task(handle, event)
    return {"ok": True}


def handle(event: dict) -> None:
    if 200 <= event["status"] < 300:
        answer = event["body"]
        print(event["request_id"], answer["answer"], len(answer["citations"]))
    elif event["status"] >= 500:
        ...  # not billed: resubmit the job with attempt + 1
```

```javascript Node (Express) theme={null}
import express from "express";
import { verifyWebhookSignature } from "scrapebadger";

const app = express();
const secret = process.env.SCRAPEBADGER_WEBHOOK_SECRET;
const seen = new Set(); // use Redis (SET NX with a TTL) in production

app.post(
  "/hooks/scrapebadger",
  express.raw({ type: "application/json", limit: "5mb" }), // the exact signed bytes
  (req, res) => {
    let event;
    try {
      event = JSON.parse(req.body.toString("utf8"));
    } catch {
      return res.sendStatus(400);
    }
    const signature = req.get("X-ScrapeBadger-Signature") ?? "";
    if (!verifyWebhookSignature(secret, req.body, signature, { sentAt: event.sent_at })) {
      return res.sendStatus(401);
    }
    res.sendStatus(200);
    if (seen.has(event.request_id)) return; // a repeat delivery
    seen.add(event.request_id);
    if (event.status >= 200 && event.status < 300) {
      console.log(event.request_id, event.body.answer, event.body.citations.length);
    } else if (event.status >= 500) {
      // not billed: resubmit the job with attempt + 1
    }
  },
);

app.listen(3000);
```

See [Async requests and webhooks](https://docs.scrapebadger.com/long-running-requests.md) for the full payload,
retries, delivery status and the webhook secret.

> [!WARNING]
>
> Perplexity is non-deterministic. The same prompt can return different wording
> and different sources on each call. For tracking, sample on a schedule and
> aggregate.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.