Ask Perplexity
curl --request GET \
--url https://scrapebadger.com/v1/perplexity/ask \
--header 'X-API-Key: <x-api-key>'import requests
url = "https://scrapebadger.com/v1/perplexity/ask"
headers = {"X-API-Key": "<x-api-key>"}
response = requests.get(url, headers=headers)
print(response.text)const options = {method: 'GET', headers: {'X-API-Key': '<x-api-key>'}};
fetch('https://scrapebadger.com/v1/perplexity/ask', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://scrapebadger.com/v1/perplexity/ask",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"X-API-Key: <x-api-key>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://scrapebadger.com/v1/perplexity/ask"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("X-API-Key", "<x-api-key>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://scrapebadger.com/v1/perplexity/ask")
.header("X-API-Key", "<x-api-key>")
.asString();require 'uri'
require 'net/http'
url = URI("https://scrapebadger.com/v1/perplexity/ask")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
request["X-API-Key"] = '<x-api-key>'
response = http.request(request)
puts response.read_body{
"prompt": "<string>",
"answer": "<string>",
"answer_markdown": {},
"citations": [
{
"url": "<string>",
"title": {},
"snippet": {},
"domain": {},
"source_type": {},
"pub_date_utc": {},
"published_at": {},
"last_updated": {},
"ref_index": {},
"start_index": {},
"end_index": {},
"matched_text": {}
}
],
"search_results": [
{}
],
"source_domains": [
"<string>"
],
"related_questions": [
"<string>"
],
"images": [
{}
],
"videos": [
{}
],
"web_search_triggered": true,
"truncated": true,
"search_queries": [
"<string>"
],
"search_query_str": "<string>",
"whole_prompt": true,
"focus": "<string>",
"model": {},
"backend_uuid": {},
"country": "<string>",
"location": {},
"answer_length": 123,
"citation_count": 123,
"latency_ms": 123,
"created_utc": {},
"created_at": {},
"answer_html": "<string>",
"raw": {}
}Ask
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.
GET
/
v1
/
perplexity
/
ask
Ask Perplexity
curl --request GET \
--url https://scrapebadger.com/v1/perplexity/ask \
--header 'X-API-Key: <x-api-key>'import requests
url = "https://scrapebadger.com/v1/perplexity/ask"
headers = {"X-API-Key": "<x-api-key>"}
response = requests.get(url, headers=headers)
print(response.text)const options = {method: 'GET', headers: {'X-API-Key': '<x-api-key>'}};
fetch('https://scrapebadger.com/v1/perplexity/ask', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://scrapebadger.com/v1/perplexity/ask",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"X-API-Key: <x-api-key>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://scrapebadger.com/v1/perplexity/ask"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("X-API-Key", "<x-api-key>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://scrapebadger.com/v1/perplexity/ask")
.header("X-API-Key", "<x-api-key>")
.asString();require 'uri'
require 'net/http'
url = URI("https://scrapebadger.com/v1/perplexity/ask")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
request["X-API-Key"] = '<x-api-key>'
response = http.request(request)
puts response.read_body{
"prompt": "<string>",
"answer": "<string>",
"answer_markdown": {},
"citations": [
{
"url": "<string>",
"title": {},
"snippet": {},
"domain": {},
"source_type": {},
"pub_date_utc": {},
"published_at": {},
"last_updated": {},
"ref_index": {},
"start_index": {},
"end_index": {},
"matched_text": {}
}
],
"search_results": [
{}
],
"source_domains": [
"<string>"
],
"related_questions": [
"<string>"
],
"images": [
{}
],
"videos": [
{}
],
"web_search_triggered": true,
"truncated": true,
"search_queries": [
"<string>"
],
"search_query_str": "<string>",
"whole_prompt": true,
"focus": "<string>",
"model": {},
"backend_uuid": {},
"country": "<string>",
"location": {},
"answer_length": 123,
"citation_count": 123,
"latency_ms": 123,
"created_utc": {},
"created_at": {},
"answer_html": "<string>",
"raw": {}
}Ask the real
Every response tells you which case you got.
Log both fields when you compare answers over time: two answers to the same
prompt are only comparable search for search when their
If no exit in that market answers in time you get a
Perplexity now answers for Tokyo. The response carries the value next to
An unknown city or a malformed
An async call is billed once, when it completes. See Async requests and webhooks for webhooks, signatures and the SDK helpers.
See Async requests and webhooks for the full payload,
retries, delivery status and the webhook secret.
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
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.
Authorization
Query Parameters
The question to ask. Maximum 4,096 characters. Each request is standalone,
so include all the context you need here.
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.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.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.Show Cities
Show 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
Retrieval focus:
web, scholar (academic sources) or social
(discussions and forums).Also return
answer_html: the answer rendered as an HTML fragment, with each
[n] citation linked to its source. See Answer HTML. Same price.Also return
raw: Perplexity’s own answer object, exactly as it sent it. See
Raw response. Same price.Response
The sources the answer actually references.
Show Citation
Show Citation
The full set Perplexity retrieved, cited or not. Same fields as
Citation without the answer offsets, plus cited (boolean).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.
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.The market that actually answered. Without
strict_country it can differ from the country you asked for.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.Only with
html=true. The answer as an HTML fragment. See Answer HTML.Only with
raw=true. Perplexity’s final answer object as received. See Raw response.Example
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
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);
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 |
search_query_str is the phrase
that was searched, and whole_prompt is true when that phrase was your whole
prompt:
{
"search_query_str": "CRM tools small businesses US",
"whole_prompt": false
}
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 defaultcountry 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:
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
503, which is not billed.
Retry later rather than dropping strict_country:
503 Response
{
"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 asbest 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:
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
country:
{
"country": "JP",
"location": "tokyo"
}
lat,lng fails before any attempt is made. It
is not billed:
400 Response
{
"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. Withhtml=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-refmatchesref_indexincitations. - Safe to embed: raw HTML inside the answer is dropped, and so are
javascript:anddata:links. - A fragment, not a page: no
<html>or<body>and no styles. Wrap it in your own page and stylea.citationas you like.
<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
Withraw=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. |
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"
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 returns202 at
once, and each answer arrives at your server as a signed webhook.
- Submit each ask with
X-Callback-URL(orcallback_url) and anIdempotency-Keymade from your own job id. Store therequest_idyou get back with the job. - Verify each delivery’s
X-ScrapeBadger-Signaturewith your webhook secret. - Deduplicate on
request_id. Deliveries are at least once, so the same answer can arrive twice. - Resubmit
5xxfailures with a new key. A failed ask is not billed. Its old key would only replay the same failure. Don’t resubmit a4xx: 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’s202 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.
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"}'
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())
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
}
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, sets how fast you can submit.Receive
The receiver checks the signature, skips repeats and answers before it does any work. A2xx within 10 s counts as delivered. Anything slower is sent again.
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
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);
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.

