Perplexity API
Submit Perplexity prompts, configure inputs, poll snapshots, and handle results and errors with WebScrapingAPI.
Collect Perplexity answers and source information returned for your prompts. Submit one or more prompts as an asynchronous job, save the returned snapshot_id, then retrieve the completed records.
Before you start
You need a WebScrapingAPI key with access to perplexity_async and available request credits. In the Dashboard, open Products → AI → Perplexity API → View Details and choose Request Quote to open Support with Request Demo selected. Use the form to arrange access and pricing. A visible scraper card does not automatically enable API access.
Send requests from your server and keep the API key private. Authenticate with your WebScrapingAPI key.
API endpoint
https://ecom.webscrapingapi.com/v1| Action | Method | Query parameters |
|---|---|---|
| Submit prompts | POST | api_key, engine=perplexity_async, type=prompt |
| Retrieve a snapshot | GET | api_key, snapshot_id |
Use Content-Type: application/json for submission. Retrieval uses the same API key and does not include engine, type, or a request body.
Parameters
Submission query
| Parameter | Required | Description |
|---|---|---|
api_key | Yes | Your WebScrapingAPI key, authorized for this engine. |
engine | Yes | Use perplexity_async for the asynchronous workflow documented here. |
type | No | Defaults to prompt. Include type=prompt explicitly as in the examples. |
Prompt objects
The body must be a non-empty JSON array, even for a single prompt. Each object represents one input.
| Field | Required | Type | Description |
|---|---|---|---|
prompt | Yes | string | Non-empty prompt text. Whitespace-only prompts are rejected. |
url | No | string | Defaults to https://www.perplexity.ai. Use HTTPS on this AI service's hostname; credentials and explicit ports are rejected. |
country | No | string | Two-letter country code, such as US or GB. Defaults to US; an empty string lets the scraper select the location automatically. Lowercase codes are accepted and normalized. A body value overrides the optional country query parameter. |
index | No | integer | Positive input identifier, assigned 1, 2, and so on within each batch when omitted. Supply a JSON number, not a quoted string. |
additional_prompt | No | string | Additional follow-up prompt to include with this input. |
Limits and credits
The default server limit is 50 prompt objects per request. Deployments can use a different batch limit; confirm your enabled limit with support before sending larger batches. Regardless of that limit, at most 5000 prompt objects are accepted. Split larger workloads into separate batches.
The JSON request body must fit within 2 MiB. The default response download limit is 3 MiB; large batches or HTML answers can exceed it, so use smaller batches when responses are large.
A successful submission consumes one request credit per prompt. Snapshot retrieval consumes zero additional request credits, but your key must remain active, authorized, and within its account limits. A job or individual record that fails after submission does not automatically refund its submission credits.
Submit prompts
Replace YOUR_API_KEY with your key. Examples require cURL 7.87+, Node.js 18+ (native fetch), Python 3 with requests, PHP with the cURL extension, Go 1.16+, Java 11+, .NET 6+, or Ruby with its standard library, according to the selected tab.
API_URL='https://ecom.webscrapingapi.com/v1'
API_KEY="YOUR_API_KEY"
curl --request POST --url "$API_URL" \
--url-query "api_key=$API_KEY" \
--url-query 'engine=perplexity_async' \
--url-query "type=prompt" \
--header "Content-Type: application/json" \
--data '[
{
"url": "https://www.perplexity.ai",
"prompt": "Compare three tools for monitoring brand mentions and cite your sources.",
"country": "US"
}
]' \
--connect-timeout 30 --max-time 120 --fail-with-bodyconst url = new URL("https://ecom.webscrapingapi.com/v1");
url.search = new URLSearchParams({
"api_key": "YOUR_API_KEY",
"engine": "perplexity_async",
"type": "prompt"
}).toString();
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify([
{
"url": "https://www.perplexity.ai",
"prompt": "Compare three tools for monitoring brand mentions and cite your sources.",
"country": "US"
}
]),
signal: AbortSignal.timeout(120_000),
});
if (!response.ok) throw new Error(await response.text());
console.log(JSON.stringify(await response.json(), null, 2));import json
import requests
params = {
"api_key": "YOUR_API_KEY",
"engine": "perplexity_async",
"type": "prompt"
}
payload = [
{
"url": "https://www.perplexity.ai",
"prompt": "Compare three tools for monitoring brand mentions and cite your sources.",
"country": "US"
}
]
response = requests.post(
"https://ecom.webscrapingapi.com/v1",
params=params,
json=payload,
timeout=(30, 120),
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))<?php
$params = [
'api_key' => 'YOUR_API_KEY',
'engine' => 'perplexity_async',
'type' => 'prompt',
];
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://ecom.webscrapingapi.com/v1?' . $query);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_TIMEOUT => 120,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => '[{"url":"https://www.perplexity.ai","prompt":"Compare three tools for monitoring brand mentions and cite your sources.","country":"US"}]',
]);
$response = curl_exec($ch);
if ($response === false) throw new RuntimeException(curl_error($ch));
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status >= 400) throw new RuntimeException("HTTP $status: $response");
echo $response;package main
import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
func main() {
target, err := url.Parse("https://ecom.webscrapingapi.com/v1")
if err != nil { panic(err) }
params := url.Values{}
params.Set("api_key", "YOUR_API_KEY")
params.Set("engine", "perplexity_async")
params.Set("type", "prompt")
target.RawQuery = params.Encode()
req, err := http.NewRequest("POST", target.String(), strings.NewReader("[{\"url\":\"https://www.perplexity.ai\",\"prompt\":\"Compare three tools for monitoring brand mentions and cite your sources.\",\"country\":\"US\"}]"))
if err != nil { panic(err) }
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 120 * time.Second}
response, err := client.Do(req)
if err != nil { panic(err) }
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
if err != nil { panic(err) }
if response.StatusCode >= 400 { panic(fmt.Sprintf("HTTP %d: %s", response.StatusCode, responseBody)) }
fmt.Println(string(responseBody))
}import java.net.URI;
import java.net.URLEncoder;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws Exception {
Map<String, String> params = Map.of(
"api_key", "YOUR_API_KEY",
"engine", "perplexity_async",
"type", "prompt"
);
String query = params.entrySet().stream().map(entry ->
URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "=" +
URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)
).collect(Collectors.joining("&"));
HttpRequest request = HttpRequest.newBuilder(URI.create("https://ecom.webscrapingapi.com/v1?" + query))
.timeout(Duration.ofSeconds(120))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("[{\"url\":\"https://www.perplexity.ai\",\"prompt\":\"Compare three tools for monitoring brand mentions and cite your sources.\",\"country\":\"US\"}]"))
.build();
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) throw new RuntimeException("HTTP " + response.statusCode() + ": " + response.body());
System.out.println(response.body());
}
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
var parameters = new Dictionary<string, string>
{
["api_key"] = "YOUR_API_KEY",
["engine"] = "perplexity_async",
["type"] = "prompt",
};
var url = new UriBuilder("https://ecom.webscrapingapi.com/v1")
{
Query = string.Join("&", parameters.Select(pair =>
$"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(pair.Value)}")),
};
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(120) };
using var body = new StringContent("[{\"url\":\"https://www.perplexity.ai\",\"prompt\":\"Compare three tools for monitoring brand mentions and cite your sources.\",\"country\":\"US\"}]", Encoding.UTF8, "application/json");
using var response = await client.PostAsync(url.Uri, body);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());require "json"
require "net/http"
require "uri"
uri = URI('https://ecom.webscrapingapi.com/v1')
uri.query = URI.encode_www_form(
api_key: 'YOUR_API_KEY',
engine: 'perplexity_async',
type: 'prompt'
)
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request.body = '[{"url":"https://www.perplexity.ai","prompt":"Compare three tools for monitoring brand mentions and cite your sources.","country":"US"}]'
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == "https"
http.open_timeout = 30
http.read_timeout = 120
response = http.request(request)
raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(JSON.parse(response.body))Submission response
A successful submission returns HTTP 200 with a snapshot ID. This acknowledges the job; it does not mean the answer is ready. The ID below is illustrative.
{
"snapshot_id": "s_example_snapshot"
}Save this ID before polling. If a submission times out before you receive an ID, it may already have created a job. Submission has no idempotency guarantee; automatically resending it can create another job and consume more credits.
Retrieve results
Replace YOUR_SNAPSHOT_ID with the submitted ID. Keep the same API key that submitted the prompts, and retain access to perplexity_async. Rotating the API key removes access to snapshots submitted with the previous key.
Snapshot access expires after 30 days, and results may become unavailable sooner. Retrieve completed records promptly and save them in your own storage.
API_URL='https://ecom.webscrapingapi.com/v1'
API_KEY="YOUR_API_KEY"
SNAPSHOT_ID="YOUR_SNAPSHOT_ID"
curl --request GET --url "$API_URL" \
--url-query "api_key=$API_KEY" \
--url-query "snapshot_id=$SNAPSHOT_ID" \
--connect-timeout 30 --max-time 120 --fail-with-bodyconst url = new URL("https://ecom.webscrapingapi.com/v1");
url.search = new URLSearchParams({
"api_key": "YOUR_API_KEY",
"snapshot_id": "YOUR_SNAPSHOT_ID"
}).toString();
const response = await fetch(url, {
method: "GET",
signal: AbortSignal.timeout(120_000),
});
if (!response.ok) throw new Error(await response.text());
console.log(JSON.stringify(await response.json(), null, 2));import json
import requests
params = {
"api_key": "YOUR_API_KEY",
"snapshot_id": "YOUR_SNAPSHOT_ID"
}
response = requests.get(
"https://ecom.webscrapingapi.com/v1",
params=params,
timeout=(30, 120),
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))<?php
$params = [
'api_key' => 'YOUR_API_KEY',
'snapshot_id' => 'YOUR_SNAPSHOT_ID',
];
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://ecom.webscrapingapi.com/v1?' . $query);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_TIMEOUT => 120,
]);
$response = curl_exec($ch);
if ($response === false) throw new RuntimeException(curl_error($ch));
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status >= 400) throw new RuntimeException("HTTP $status: $response");
echo $response;package main
import (
"fmt"
"io"
"net/http"
"net/url"
"time"
)
func main() {
target, err := url.Parse("https://ecom.webscrapingapi.com/v1")
if err != nil { panic(err) }
params := url.Values{}
params.Set("api_key", "YOUR_API_KEY")
params.Set("snapshot_id", "YOUR_SNAPSHOT_ID")
target.RawQuery = params.Encode()
req, err := http.NewRequest("GET", target.String(), nil)
if err != nil { panic(err) }
client := &http.Client{Timeout: 120 * time.Second}
response, err := client.Do(req)
if err != nil { panic(err) }
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
if err != nil { panic(err) }
if response.StatusCode >= 400 { panic(fmt.Sprintf("HTTP %d: %s", response.StatusCode, responseBody)) }
fmt.Println(string(responseBody))
}import java.net.URI;
import java.net.URLEncoder;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws Exception {
Map<String, String> params = Map.of(
"api_key", "YOUR_API_KEY",
"snapshot_id", "YOUR_SNAPSHOT_ID"
);
String query = params.entrySet().stream().map(entry ->
URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "=" +
URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)
).collect(Collectors.joining("&"));
HttpRequest request = HttpRequest.newBuilder(URI.create("https://ecom.webscrapingapi.com/v1?" + query))
.timeout(Duration.ofSeconds(120))
.GET()
.build();
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) throw new RuntimeException("HTTP " + response.statusCode() + ": " + response.body());
System.out.println(response.body());
}
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
var parameters = new Dictionary<string, string>
{
["api_key"] = "YOUR_API_KEY",
["snapshot_id"] = "YOUR_SNAPSHOT_ID",
};
var url = new UriBuilder("https://ecom.webscrapingapi.com/v1")
{
Query = string.Join("&", parameters.Select(pair =>
$"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(pair.Value)}")),
};
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(120) };
using var response = await client.GetAsync(url.Uri);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());require "json"
require "net/http"
require "uri"
uri = URI('https://ecom.webscrapingapi.com/v1')
uri.query = URI.encode_www_form(
api_key: 'YOUR_API_KEY',
snapshot_id: 'YOUR_SNAPSHOT_ID'
)
request = Net::HTTP::Get.new(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == "https"
http.open_timeout = 30
http.read_timeout = 120
response = http.request(request)
raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(JSON.parse(response.body))While the job is running
The API returns HTTP 200 with an in-progress status:
{
"status": "Running",
"message": "The snapshot is still being processed."
}Poll the same ID again after a delay. A practical starting interval is five seconds, increasing to 30 seconds for long-running jobs. Set a maximum wait in your application and save the snapshot ID so you can resume later. Completion time varies; an HTTP 200 response alone does not mean the job has completed.
Completed results
Completed answer records are returned in result. This abbreviated example illustrates the response structure with sample answer text.
{
"result": [
{
"url": "https://www.perplexity.ai",
"prompt": "Compare three tools for monitoring brand mentions and cite your sources.",
"answer_text": "An example comparison returned by the assistant."
}
]
}Records may include answer_text, answer_html, links, citations, supporting sources, or other fields specific to the AI service. Availability depends on the prompt and the answer. Handle missing fields, and inspect every record for error or error_code before treating it as an answer. If inputs are echoed in the result, use them or their index to match records to your batch rather than relying on response order.
For each polling response, check the HTTP status first. Continue polling only for status: "Running". Process result when present; preserve other responses for error handling rather than treating every HTTP 200 object as a finished answer.
Errors and retries
| HTTP status | Meaning | What to do |
|---|---|---|
400 | Invalid input or query combination; some download or network failures also use this status. | Read error, check the input and batch size, and use snapshot_id without engine for retrieval. |
401 | Missing, invalid, conflicting, or expired credentials; insufficient credits or account concurrency exhaustion. | Check the key and available credits. Reduce simultaneous requests if the error reports account concurrency. |
403 | Engine access is not enabled, or the snapshot is unknown, expired, belongs to another key, or is no longer authorized. | Confirm access with support and use the submitting key. |
413 | Request body exceeds 2 MiB. | Split the batch or shorten inputs. |
429 | Global request capacity is exhausted. | Reduce simultaneous requests and retry after a delay. |
502 | The scraper failed or returned an invalid response. | Retry retrieval with backoff; investigate before repeating a submission. |
503 | Authentication or snapshot access is temporarily unavailable. | Retry retrieval later with the same ID and key. |
Error payloads can contain an error string or a structured failure with status and status_code. Malformed or oversized request bodies can return an HTML error page, so check the HTTP status and content type before assuming a response is JSON. A completed batch can also contain individual failed records even when HTTP status is 200.
Use bounded retries for retrieval. Do not repeatedly resubmit a prompt while its snapshot is still running.
Use Postman
Download the collection at the top of this page and set its api_key variable. Send the starter request; its response script saves the returned ID in the snapshot_id collection variable. Then send Perplexity API retrieve results until the response contains completed results. You can also paste a previously returned snapshot ID into that variable.
Other AI scrapers
ChatGPT · Google Gemini · Perplexity · Copilot · Google AI Mode