Perplexity API key setup: credits, the Agent API and where the key lives
Create a Perplexity API key, buy credits before the first call, keep it on your server as PERPLEXITY_API_KEY, and move old Sonar code to the Agent API.
The short version
Sign in to the Perplexity API Console at console.perplexity.ai, click API keys in the sidebar and choose Generate API Key. Before that key does anything useful, an Admin has to buy credits on the Billing page, because Perplexity bills from a prepaid balance. Store the key on your host as PERPLEXITY_API_KEY, the name Perplexity's quickstart and official SDKs read, and send it only from server code in an Authorization: Bearer header.
One change matters if you are following an older tutorial. Perplexity's migration guide says Sonar Chat Completions support ended on September 27, 2026. New code should call the Agent API at https://api.perplexity.ai/v1/agent, which follows the OpenAI Responses format, instead of chat.completions.create() with model: "sonar".
API groups are now called Projects
Older guides talk about API groups. The current docs call the workspace a Project: the place in the API Portal where your organization manages billing, creates keys, invites members and watches usage. You set it up under Settings in the Project part of the sidebar, with the organization's name, address and tax details.
Roles matter even on a team of two. Only Admins can open the Billing page, and Members can neither see Billing nor view the usage metrics in the console. Make the person who owns the card an Admin, and give a contractor who only needs to build against the API a Member seat.
Create the key and fund it
Four steps, and the last one is the one people skip. The docs are blunt about it: when you run out of credits, your API keys are blocked until you add to the balance, and the FAQ adds that requests can then come back as 402 Payment Required. Auto reload adds credits automatically when the balance drops below a threshold, which turns an outage into a line on your card statement.
- Open
console.perplexity.ai, choose or create the Project for this app, and fill in the organization details under Settings. - Click API keys in the sidebar, then + Generate API Key. Copy it straight into your host's variables as
PERPLEXITY_API_KEY, and make a second key for local development that lives in a.envfile git ignores. - On the Billing page, click Add payment method. Perplexity says adding a card does not charge it; payments run through Stripe, and Manage opens the Stripe portal.
- Buy credits with Buy more credits, then click Change preferences next to Auto reload and turn it on.
Which endpoint and which model
One Perplexity key now opens several APIs. The Agent API (POST /v1/agent, with /v1/responses accepted as an alias for the OpenAI SDK) answers questions and can search the web and cite sources. The Search API at /search returns raw search results for you to use yourself, and the Orchestrator API at https://api.perplexity.ai/orchestrator/v1 uses the OpenAI Chat Completions format. For a feature that answers a user's question with sources, the Agent API is where the docs start.
You pick behaviour in one of two ways. The effort field selects a ready-made configuration: fast for quick factual lookups with inline citations, low for everyday research, medium for multi-hop research across many sources, high for the broadest coverage, and xhigh for long agentic work that can run code in a sandbox. Every level includes the web_search tool. Or you set model to a provider-prefixed ID; the models page lists IDs such as perplexity/sonar, openai/gpt-5.6-sol and anthropic/claude-sonnet-5-5, each with its own published price, and notes that those rates may differ from the provider's list prices. A request cannot set both effort and profile.
If you have Sonar code, the migration guide gives starting points: sonar and sonar-pro become effort: "fast", sonar-reasoning-pro becomes low, and sonar-deep-research becomes high. The prompt moves from a messages array to input, max_tokens is renamed max_output_tokens, and the answer is read from output_text instead of choices[0].message.content. Synchronous and streaming Sonar requests keep working for now while Perplexity reformulates them as Agent API requests, but asynchronous Sonar requests are no longer supported and move to background runs.
curl https://api.perplexity.ai/v1/agent \
-H "Authorization: Bearer $PERPLEXITY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"effort": "fast", "input": "What changed in the latest Node.js LTS release?"}'Call it from a server route
The official TypeScript package is @perplexity-ai/perplexity_ai and the Python package is perplexityai. Both pick up PERPLEXITY_API_KEY from the environment, so the key never appears in your code. You can also point the OpenAI SDK at https://api.perplexity.ai/v1 and call responses.create(), which lets an app already built on OpenAI switch with a base URL and a key. Perplexity warns that the two APIs are not identical and some defaults differ, so test before you swap.
One detail catches people out. A request that sends only model and input answers from the model's own knowledge and returns no citations. If the reason you chose Perplexity is fresh, sourced answers, set an effort level or add the web_search tool, and read the sources from the output item of type search_results, where each [n] marker in the text points at the result whose id is n.
// app/api/research/route.ts
import Perplexity from '@perplexity-ai/perplexity_ai'
const client = new Perplexity() // reads PERPLEXITY_API_KEY
export async function POST(req: Request) {
// Check the session and a per-user limit here, before spending credits.
const { question } = await req.json()
const response = await client.responses.create({
effort: 'fast', // includes web_search, so the answer carries citations
input: question,
})
return Response.json({ text: response.output_text })
}Keep the key and the route private
Perplexity's Projects page calls API keys sensitive credentials. A key in browser code can be read by anyone who opens the network tab, so never give the variable a NEXT_PUBLIC_ or VITE_ prefix: those prefixes exist to copy values into the browser bundle. After adding or changing the variable on your host, redeploy so the running app actually has it.
Moving the call to the server is only half of it. If /api/research answers anyone who posts to it, a stranger can spend your credits through your own endpoint without ever seeing the key. Require a signed-in user, count requests per user, and set max_output_tokens so a single answer has a known ceiling.
Rate limits and usage tiers
Limits grow with what you have spent in total. New accounts start in Tier 0, and Tiers 1 to 5 begin at cumulative purchases of $50, $250, $500, $1,000 and $5,000. The tier follows lifetime purchases rather than your current balance, the move up is automatic, and Perplexity says you keep a tier permanently.
At Tier 0 the Agent API allows 1 request per second, shared by every model and every key in the organization, with token budgets per model of 5,000,000 tokens a minute and 300,000,000 an hour. One request a second is enough for a prototype and tight for a launch day, so put a small queue in front of the API early. Successful responses carry x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-used and x-ratelimit-reset headers that are worth logging.
The errors you will meet first
The status code, and for a 429 the error.type, tells you whether a retry can ever succeed. Two more details from the rate-limit page shape the retry code. A 429 carries a Retry-After header but none of the x-ratelimit-* headers, so wait for what the header says. And a request refused for tokens still counts as one request against the per-second limit, so a tight retry loop makes the problem worse.
| Error | What it means | What to do |
|---|---|---|
| 401 | The request could not be authenticated | Check the key is current and not revoked, and that it is sent as Authorization: Bearer followed by the key |
| 402 Payment Required | The account ran out of credits and its keys are blocked | A retry will not help. Buy credits and turn on auto reload |
429 request_rate_limit_exceeded | Too many requests per second | Wait the Retry-After interval, normally 1 second, then retry |
429 token_rate_limit_exceeded | The per-minute or per-hour token budget is used up; the message names the window | Wait for Retry-After, which includes up to 10 seconds of random delay |
429 overloaded | Not your limit: upstream model capacity is full | Retry with backoff, or list fallback models in models |
Rotating or revoking a key
The Projects page says keys can be revoked for security purposes, and a revoked key stops authenticating, which shows up in your app as a 401. To rotate without downtime, work in this order: generate a new key, put it in your host's variables and redeploy, confirm a real request succeeds, and only then revoke the old one. If a key has leaked, revoke it first and accept a few minutes of errors, then check the usage metrics in the console for the period it was exposed.
When another provider fits better
Perplexity earns its place when answers need current web results with citations. If your feature only asks a model to write, summarise or classify text you already have, a direct model provider is simpler: one less layer between you and the model, and documentation written for exactly that job. The OpenAI and Anthropic setup posts linked below cover those keys, and OpenRouter is the better fit if you want many models behind one key and one bill. Perplexity does serve other labs' models through the same key at rates it publishes per model, so compare those with the lab's own price before routing plain text generation through it.
What Shipyard does here
Shipyard writes keys for Anthropic, OpenAI and OpenRouter into your host, on the server side only. It does not write Perplexity keys. To add Perplexity to an app Shipyard set up, create and fund the key as above, add PERPLEXITY_API_KEY to your Railway or Vercel project yourself and redeploy. Everything else Shipyard configured keeps working as it is.
Sources
- Perplexity quickstartdocs.perplexity.ai
- Perplexity: Projects and billingdocs.perplexity.ai
- Perplexity: rate limits and usage tiersdocs.perplexity.ai
- Perplexity: Agent API quickstartdocs.perplexity.ai
- Perplexity: effort levelsdocs.perplexity.ai
- Perplexity: Agent API modelsdocs.perplexity.ai
- Perplexity: OpenAI compatibilitydocs.perplexity.ai
- Perplexity: migrate from Sonar to the Agent APIdocs.perplexity.ai
- Perplexity: how to migrate from Sonardocs.perplexity.ai
- Perplexity: frequently asked questionsdocs.perplexity.ai
Launch in an hour, not a weekend
Shipyard connects your accounts once, then sets up the domain, hosting, database, email and payments for every new product.