# Making requests

Call any API with POST /v1/run/{sku}. Build the input from the schema, read the envelope, handle not-found results, and trim large responses with fields, max_items and summary.

`POST https://api.primaryapi.com/v1/run/{sku}`

Auth: API key with run or full access, or a dashboard session

Every API in the catalog is called the same way: one `POST` with a JSON body. The body holds the SKU's own input fields and, optionally, [routing controls](/docs/routing-and-failover).

| Part | Value |
|---|---|
| Path | `/v1/run/{sku}`, for example `/v1/run/reddit.search`. SKUs are case-insensitive. |
| Headers | `Authorization: Bearer …` (or `X-API-Key`), `Content-Type: application/json`; optional `Idempotency-Key` ([Idempotency](/docs/idempotency)) and `Prefer` ([Durable requests](/docs/durable-requests)) |
| Query | Optional `fields`, `max_items`, `summary` to shrink the response (below) |
| Body | A JSON object, at most 2 MB |

## Build the input from the schema

Each SKU publishes its input as a JSON Schema (draft 2020-12). Read it on the API's reference page or fetch it, no key needed:

```bash
curl -sS "https://api.primaryapi.com/v1/apis/reddit.search" | jq '.inputSchema'
```

```json
{
  "type": "object",
  "properties": {
    "query": { "type": "string", "minLength": 1, "maxLength": 500, "description": "Search query." },
    "sort": { "type": "string", "enum": ["relevance", "hot", "top", "new", "comments"], "default": "relevance" },
    "timeframe": { "type": "string", "enum": ["hour", "day", "week", "month", "year", "all"], "default": "all" },
    "limit": { "type": "integer", "minimum": 1, "maximum": 100, "default": 25 },
    "cursor": { "type": "string", "minLength": 1, "description": "Opaque pagination cursor: pass the previous response's nextCursor." }
  },
  "required": ["query"]
}
```

The same response also carries `outputSchema`, worked `examples`, the `price`, and the API's measured 30-day `health`.

Validation is strict and happens before anything runs:

- **Unknown fields are rejected**, never ignored, so a typo such as `"qurey"` fails loudly instead of silently returning the wrong thing.
- Missing required fields, wrong types and out-of-range values are rejected.
- Defaults from the schema are applied (above, `limit` becomes `25` when you leave it out). The defaults count for pricing: a per-result API holds credits for the default `limit`.

A rejected request answers `400 invalid_input` and costs nothing. `details` lists every problem with its path:

```json title="400 Bad Request"
{
  "code": "invalid_input",
  "error": "Unrecognized key: \"qurey\"",
  "requestId": "req_01JBXN0C2E4G6J8M0P2R4T6V8X",
  "details": [
    { "code": "unrecognized_keys", "keys": ["qurey"], "path": [], "message": "Unrecognized key: \"qurey\"" }
  ]
}
```

## Read the response

A finished call answers `200 OK` with the envelope (shortened here to one of the ten posts):

```json title="200 OK"
{
  "output": {
    "found": true,
    "data": {
      "posts": [
        { "id": "1abc23", "title": "…", "author": "…", "subreddit": "MechanicalKeyboards", "score": 412, "numComments": 87, "…": "…" }
      ],
      "nextCursor": "eyJhZnRlciI6InQzXzFhYmMyMyJ9"
    }
  },
  "provider": "PrimaryAPI",
  "credits": 2,
  "items": 1,
  "requestId": "req_01JBXK6Y2N9V8T4R3Q2P1M0A7Z",
  "nextCursor": "eyJhZnRlciI6InQzXzFhYmMyMyJ9"
}
```

| Field | Type | Meaning |
|---|---|---|
| `output.found` | boolean | Whether the thing you asked for exists. `false` is still a success. |
| `output.data` | object or null | The result, shaped by the SKU's `outputSchema`. `null` when `found` is `false`. |
| `output.reason` | string | Only when `found` is `false`: `not_found`, `private`, `suspended`, `no_results`, … |
| `provider` | string | Always `PrimaryAPI`. Kept for compatibility; which upstream answered is never exposed. |
| `credits` | integer | What this call took from your balance, in whole credits. `0` when nothing was charged. |
| `items` | integer | Billable results. For per-result APIs, the rows returned; otherwise `1` for a hit, `0` for a miss. |
| `requestId` | string | The call's id (`req_…`). Also sent as the `X-Request-Id` header. |
| `nextCursor` | string or null | List APIs only: pass it back as `cursor` for the next page; `null` at the end ([Pagination](/docs/pagination)). |
| `hint` | string | Optional advisory note with a machine prefix, for example `truncated: …` when `max_items` shortened a list. Never needed for correctness. |
| `replayed` | boolean | `true` when this is a stored result returned for a repeated `Idempotency-Key` (free). |

Other responses:

- `202 Accepted` with a request snapshot when the call is still running at the end of the wait window (10 seconds by default). The work continues; poll `GET /v1/requests/{id}`. See [Durable requests](/docs/durable-requests).
- An error with `{ code, error, requestId }` and a 4xx or 5xx status. Errors are never charged. See [Errors](/docs/errors).

Response headers worth logging: `X-Request-Id` on every response, `Idempotency-Replayed: true|false` when you sent an `Idempotency-Key`, and `Location`, `Retry-After` and `Preference-Applied` on a `202`.

## Not found is a successful answer

Asking for a profile that does not exist, a private account, or a search with no matches is a valid question with a valid answer:

```json title="200 OK"
{
  "output": { "found": false, "data": null, "reason": "not_found" },
  "provider": "PrimaryAPI",
  "credits": 0,
  "items": 0,
  "requestId": "req_01JBXP4H6K8M0Q2S4V6X8Z0B2D"
}
```

- It answers with HTTP 200, never 404. Branch on `output.found`, not on the status code.
- It is normally free. A few APIs bill lookups that find nothing; there a miss costs the credits of one call or result, and the API's reference page says so. `credits` always tells you what happened.
- Do not retry it hoping for a different answer: the same input gets the same result. Retry only if your input was wrong.

The `404 not_found` **error** means something else: the URL itself is unknown, such as a SKU that does not exist or a request id from another account.

```ts title="Handling all three outcomes"
const res = await fetch(`https://api.primaryapi.com/v1/run/${sku}`, { method: 'POST', headers, body: JSON.stringify(input) });
const body = await res.json();

if (res.status === 202) {
  // still running: poll GET /v1/requests/{body.requestId} (see Durable requests)
} else if (!res.ok) {
  // { code, error, requestId }: branch on code, never on the message text
  throw new Error(`${body.code}: ${body.error}`);
} else if (!body.output.found) {
  console.log(`no data (${body.output.reason}), cost ${body.credits} credits`);
} else {
  use(body.output.data);
}
```

## Make responses smaller

Large results are expensive to move and, for agents, to read. Three query parameters shrink the response without changing the call:

| Parameter | Example | Effect |
|---|---|---|
| `fields` | `fields=title,score,permalink` | Keep only these top-level keys of `output.data`, or of each row of a list result. Up to 100 names; unknown names are skipped. |
| `max_items` | `max_items=5` | Keep the first N rows of a list result. When rows were cut, `hint` says so, for example `truncated: returned 5 of 25 items (max_items); credits cover the full result`. |
| `summary` | `summary=true` | Return an outline: every array becomes `{ "count": n }` and strings longer than 120 characters are cut to a prefix ending in `…`. |

They apply in that order (`fields`, then `max_items`, then `summary`) and only to the response body.

```bash
curl -sS -X POST "https://api.primaryapi.com/v1/run/reddit.search?fields=title,score,permalink&max_items=5" \
  -H "Authorization: Bearer $PRIMARYAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query":"best mechanical keyboard","limit":25}'
```

> **Trimming shrinks the response, not the bill.** The call still fetches and charges for everything the input asked for: above, up to 25 results. `credits` and `items` describe the full result, and the full result is stored. On a per-result API, to pay for fewer results, lower the API's own input, usually `limit`.

The complete result stays available for free while it is retained (at least 24 hours): re-read it with `GET /v1/results/{requestId}`, which accepts the same three parameters. That is the cheap way to look at other fields later, and the reason agents should ask for a small slice first.

## Long-running calls

A call waits up to 10 seconds for its result. If it needs longer, you get `202 Accepted` and the call keeps running; nothing is lost and nothing is charged twice. You can wait longer in one request with `Prefer: wait=30` (up to 90 seconds), or return immediately with `Prefer: respond-async`. Set your HTTP client's timeout above the wait you ask for. [Durable requests](/docs/durable-requests) covers polling.

## Check the price first

`POST /v1/quote/{sku}` takes exactly the same body, runs the same validation and routing checks, and returns the price without calling any upstream or charging anything. Use it to show a price before a user confirms, or to validate inputs in bulk.

```json title="POST /v1/quote/facebook.search_posts → 200 OK"
{
  "sku": "facebook.search_posts",
  "credits": 17,
  "maxCredits": 33,
  "unit": "result",
  "inputValid": true
}
```

This quote is for `{"query":"product launch","limit":5}` on a per-result API. `credits` is what the call costs at the usual price if all 5 rows come back: 5 × 3.2375 credits, rounded up to 17. `maxCredits` is the most it can cost, which is what a run holds from your balance while it works; the unused part comes back at once. You pay only for the rows actually returned.

## A client checklist

- Read the key from an environment variable and send it as a Bearer token.
- Set a client timeout longer than the wait window (for example 20 seconds with the default, 100 seconds with `Prefer: wait=90`).
- Treat `202` as "still running", not as an error.
- Branch on `output.found` and on error `code`; never parse error messages.
- Send an `Idempotency-Key` with every call you might retry.
- Log `requestId` (or the `X-Request-Id` header) with every call.
