# Call your API

> Run an API over REST from any language: endpoints, keys, waiting for results, caching and responses.

Source: https://usewrit.app/docs/call/

Every API you build or install on Writ Cloud can be called over HTTPS from any language. There
are two ways in: a published REST endpoint, which gives the API a stable URL, and the run route,
which calls an API by its id without publishing anything. Both use the same API key.

## Publish and call an endpoint

-

1. **Create an API key**

In **Developers → API Keys**, create a key that can run workflows and copy it.
It starts with `wt_` and is shown once. Keep it in an environment variable such as `WRIT_API_KEY`. Scopes and rotation are on [API keys and OAuth](https://usewrit.app/docs/authentication).

-

2. **Publish the REST endpoint**

Open the API under **APIs**, go to its **Call** tab and turn on **Publish REST endpoint**. Writ names the endpoint after the API and shows its URL
with a ready-to-paste request in cURL, Python and TypeScript.

-

3. **Send a request**

The body is a JSON object with the API's inputs. The call waits for the run and returns what
it collected.

```bash
curl -X POST https://api.usewrit.app/v1/your-org/top-stories \
  -H "Authorization: Bearer $WRIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"limit": 3}'
```

```python
import os, requests

res = requests.post(
    "https://api.usewrit.app/v1/your-org/top-stories",
    headers={"Authorization": f"Bearer {os.environ['WRIT_API_KEY']}"},
    json={"limit": 3},
    timeout=130,  # a little longer than the endpoint's own wait
)
if res.status_code == 504:
    # Still running: collect it at status_url instead of calling again
    print("still running:", res.json()["status_url"])
else:
    res.raise_for_status()
    print(res.json()["data"])
    print("credits:", res.headers.get("X-Writ-Credits-Charged"))
```

```typescript
const res = await fetch("https://api.usewrit.app/v1/your-org/top-stories", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.WRIT_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ limit: 3 }),
});
const body = await res.json();
if (res.status === 504) {
  // Still running: collect it at status_url instead of calling again
  console.log("still running:", body.status_url);
} else if (!body.success) {
  throw new Error(`${body.error}: ${body.detail ?? ""}`);
} else {
  console.log(body.data, res.headers.get("X-Writ-Credits-Charged"));
}
```

```json
{
  "success": true,
  "data": {
    "stories": [
      { "rank": 1, "title": "...", "points": 412, "comments": 96, "url": "https://..." },
      { "rank": 2, "title": "...", "points": 288, "comments": 51, "url": "https://..." },
      { "rank": 3, "title": "...", "points": 175, "comments": 33, "url": "https://..." }
    ]
  }
}
```

POST `https://api.usewrit.app/v1/{ref}/{path}` 2 cr / plain call wt_ key

`{ref}` is your organization's reference and `{path}` is the endpoint's name, for example `top-stories`. You never need to build the URL yourself:
copy it from the **Call** tab, or take the base URL from **Developers → Endpoints → REST**, where every published endpoint is listed. The examples on this page use `your-org` as the reference.

### Call one function

An API built from a website usually has several functions. Add `function_name` to the
body to run just one of them. Writ also runs whatever that function needs first, such as the
sign-in, and skips the other functions. Without `function_name`, the whole API runs.

```json
{
  "function_name": "search",
  "query": "espresso machine",
  "max_results": 10
}
```

Values in the query string are inputs too, which is handy for `GET` calls. Writ
reserves two query names for itself: `async` and `max_age`.

### What comes back

A successful call answers `200` with `{"success": true, "data": ...}`, where `data` is what the run collected. A refused or failed call answers `{"success": false, "error": ..., "detail": ...}` with an HTTP error status. Endpoints published
from the **Call** tab always use this envelope.

## Long runs: wait or collect later

By default the call stays open until the run finishes. A published endpoint waits up to 120
seconds (300 for AI navigation workflows); the **Call** tab shows the exact limit.
If the run takes longer, you get `504` with a `run_id` and a `status_url`. The run keeps going, so collect it there instead of calling again.

```json
{
  "success": false,
  "error": "Execution timeout",
  "detail": "The run did not finish within 120s and is still in progress. Collect the result at status_url, or call with 'Prefer: respond-async' to avoid waiting.",
  "status": "running",
  "run_id": "run_q3Vx8bN2kLpT0aRz5mWc1yHd",
  "status_url": "https://api.usewrit.app/v1/your-org/_runs/run_q3Vx8bN2kLpT0aRz5mWc1yHd"
}
```

When you know a run is long, don't hold the connection. Send `Prefer: respond-async`,
or add `?async=true` if your client cannot set headers. Writ answers `202` at
once with a `Location` header, and you poll the `status_url` with the same key.
The **Call** tab shows this mode as **Return immediately**.

```bash
# 1. Start the run. The answer comes back at once: 202 with a run handle.
curl -X POST https://api.usewrit.app/v1/your-org/top-stories \
  -H "Authorization: Bearer $WRIT_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Prefer: respond-async" \
  -d '{"limit": 3}'

# 2. Poll the status_url with the same key until "done" is true.
curl https://api.usewrit.app/v1/your-org/_runs/run_q3Vx8bN2kLpT0aRz5mWc1yHd \
  -H "Authorization: Bearer $WRIT_API_KEY"
```

```python
import os, time, requests

headers = {"Authorization": f"Bearer {os.environ['WRIT_API_KEY']}"}

started = requests.post(
    "https://api.usewrit.app/v1/your-org/top-stories",
    headers={**headers, "Prefer": "respond-async"},
    json={"limit": 3},
).json()

run = started
while not run.get("done"):
    time.sleep(2)
    run = requests.get(started["status_url"], headers=headers).json()

if run["status"] != "success":
    raise RuntimeError(run.get("error"))
print(run["data"])
```

```typescript
const headers = { Authorization: `Bearer ${process.env.WRIT_API_KEY}` };

const started = await fetch("https://api.usewrit.app/v1/your-org/top-stories", {
  method: "POST",
  headers: { ...headers, "Content-Type": "application/json", Prefer: "respond-async" },
  body: JSON.stringify({ limit: 3 }),
}).then((r) => r.json());

let run = started;
while (!run.done) {
  await new Promise((r) => setTimeout(r, 2000));
  run = await fetch(started.status_url, { headers }).then((r) => r.json());
}
if (run.status !== "success") throw new Error(run.error);
console.log(run.data);
```

```json
{
  "success": true,
  "status": "running",
  "run_id": "run_q3Vx8bN2kLpT0aRz5mWc1yHd",
  "status_url": "https://api.usewrit.app/v1/your-org/_runs/run_q3Vx8bN2kLpT0aRz5mWc1yHd"
}
```

```json
// While it runs
{
  "success": true,
  "run_id": "run_q3Vx8bN2kLpT0aRz5mWc1yHd",
  "status": "running",
  "done": false,
  "status_url": "https://api.usewrit.app/v1/your-org/_runs/run_q3Vx8bN2kLpT0aRz5mWc1yHd"
}

// When it is finished
{
  "success": true,
  "run_id": "run_q3Vx8bN2kLpT0aRz5mWc1yHd",
  "status": "success",
  "done": true,
  "data": { "stories": [ ... ] }
}
```

An accepted poll answers `200` even when the run failed: a failed run shows `"status": "failed"` and an `error` in the body. Poll every 2 seconds (the answer carries `Retry-After: 2`).
Polls cost nothing and do not count toward your plan's calls per minute. A run stays collectable for 24 hours.

## Reuse a recent result

Some callers need fresh data on every call; others, like a dashboard, are happy with an answer
from a few minutes ago. Send `Cache-Control: max-age=N` (or `?max_age=N`) to
accept a stored answer up to `N` seconds old. If there is none, the API runs as usual.

```bash
# Accept a stored answer up to 10 minutes old, otherwise run fresh.
curl -i -X POST https://api.usewrit.app/v1/your-org/top-stories \
  -H "Authorization: Bearer $WRIT_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Cache-Control: max-age=600" \
  -d '{"limit": 3}'

# Same thing without headers:
#   POST https://api.usewrit.app/v1/your-org/top-stories?max_age=600
# Force a fresh run: Cache-Control: no-cache, or ?max_age=0
```

```python
import os, requests

res = requests.post(
    "https://api.usewrit.app/v1/your-org/top-stories",
    headers={
        "Authorization": f"Bearer {os.environ['WRIT_API_KEY']}",
        "Cache-Control": "max-age=600",
    },
    json={"limit": 3},
)
print(res.headers.get("X-Cache"), res.headers.get("Age"))  # HIT 212, or MISS 0
print(res.json()["data"])
```

```typescript
const res = await fetch("https://api.usewrit.app/v1/your-org/top-stories", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.WRIT_API_KEY}`,
    "Content-Type": "application/json",
    "Cache-Control": "max-age=600",
  },
  body: JSON.stringify({ limit: 3 }),
});
console.log(res.headers.get("X-Cache"), res.headers.get("Age")); // HIT 212, or MISS 0
console.log((await res.json()).data);
```

- `X-Cache: HIT` means you got a stored answer; `Age` says how many seconds old it is. `X-Cache: MISS` means the API ran.
- `max-age=0`, `?max_age=0` or `Cache-Control: no-cache` always runs fresh.
- A stored answer runs nothing, so it costs no credits. It still counts toward your calls per minute.

> **limit:** Answers are stored only when the endpoint has a cache window. The Call tab shows it (This endpoint keeps results for N s) or says caching is off, in which case every call runs fresh. You cannot ask for an answer older than that window.

## Run an API by its id

You can also run any API without publishing it, using its id (the number in the API's address in
the app). The key needs permission to run workflows.

POST `https://api.usewrit.app/api/v1/workflows/{id}/runs` wt_ key

```bash
curl -X POST "https://api.usewrit.app/api/v1/workflows/42/runs?wait=true&timeout=120" \
  -H "Authorization: Bearer $WRIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"form_data": {"limit": 3}}'
```

```python
import os, requests

res = requests.post(
    "https://api.usewrit.app/api/v1/workflows/42/runs",
    params={"wait": "true", "timeout": 120},
    headers={"Authorization": f"Bearer {os.environ['WRIT_API_KEY']}"},
    json={"form_data": {"limit": 3}},
    timeout=130,
)
res.raise_for_status()
print(res.json())
```

```typescript
const res = await fetch(
  "https://api.usewrit.app/api/v1/workflows/42/runs?wait=true&timeout=120",
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.WRIT_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ form_data: { limit: 3 } }),
  },
);
console.log(await res.json());
```

```json
// wait=true: the data the run collected
{
  "stories": [ { "rank": 1, "title": "...", "points": 412 } ]
}

// wait=true, but the run failed or outlived the timeout
{ "error": "Did not complete within 120s", "task_id": 91834 }

// wait=false: a handle to read later
{ "task_id": 91834, "status": "pending", "workflow": "Top stories" }
```

`wait` defaults to `true` and `timeout` to 120 seconds (10 to 300).
With `wait=false` you get a `task_id` at once. Read the outcome later:

```bash
curl https://api.usewrit.app/api/v1/workflows/42/runs/91834 \
  -H "Authorization: Bearer $WRIT_API_KEY"

{
  "task_id": 91834,
  "status": "success",
  "success": true,
  "extracted_data": { "stories": [ ... ] },
  "result_data": { "extracted_data": { "stories": [ ... ] } },
  "error": null,
  "duration_ms": 4180
}
```

> **limit:** This route always runs the whole API. To run a single function, use the published endpoint with function_name.

## Headers, limits and errors

| Response header | What it tells you |
| --- | --- |
| X-Writ-Credits-Charged | Credits this run cost, with one decimal. |
| X-Writ-Credits-Remaining | Credits you have left: the rest of the monthly allowance plus your balance. |
| X-Writ-Ran-On | cloud, cloud-wall (a cloud run that also passed a bot wall) or local (your own linked machine, free). |
| X-Cache, Age | Whether a stored answer was served, and its age in seconds. |
| X-RateLimit-Limit, X-RateLimit-Remaining | Your rate limit and what is left in the current minute. |

The credit headers come with waited answers, once the run has finished. Rate limits: each
organization gets its plan's calls per minute, and a published endpoint also allows each key 60
calls a minute by default. Past either limit you get `429` with a `Retry-After` header.

### Retry safely

Send an `Idempotency-Key` header (any unique string up to 255 characters) on a `POST`. If you send the same request again with the same key within 24 hours, Writ
replays the first answer with `Idempotency-Replayed: true` instead of running again.
A repeat that arrives while the first is still running gets `409`; the same key with a
different body gets `422`. Server errors (5xx) are never replayed, so you can retry them.

### Common errors

| Status | Meaning | What to do |
| --- | --- | --- |
| 401 | No key, a revoked or expired key, or a key that may not run this API. | Check the key and its permissions. |
| 402 | No credits left. | Wait for the monthly allowance, add funds, upgrade, or run it on Writ Desktop. |
| 404 | Unknown organization reference, no endpoint at that path, or an expired run id. | Copy the URL again from the Call tab. |
| 409 | An action that writes to a site may already have happened. | Check the site before you call again. |
| 413 | The request body is larger than your plan allows. | Send less data in one call. |
| 429 | Rate limit reached. | Wait for Retry-After seconds. |
| 504 | The run is still going after the endpoint's wait limit. | Collect it at status_url. |

A call that fails because of the site or Writ costs nothing. Every error shape and plan limit is on [Errors and limits](https://usewrit.app/docs/errors).

### Export the API description

The API's **Documentation** tab has **Download OpenAPI** and **Postman Collection**. Use them to generate a client or to import the API into another
tool. The same files are available over REST:

```bash
curl "https://api.usewrit.app/api/v1/workflows/42/api-docs?format=openapi" \
  -H "Authorization: Bearer $WRIT_API_KEY" \
  -o top-stories-openapi.json

# Other formats: markdown, postman, bundle, skill
```

## Writ Desktop and linked machines

On Writ Desktop, the same APIs answer on your own computer at `http://127.0.0.1:8131/v1`,
with a local `wlk_` key instead of a `wt_` key. Local calls are free. Turn on the
REST surface in the API's **Call** tab first.

```bash
curl -X POST "http://127.0.0.1:8131/v1/workflows/7/run?wait=true" \
  -H "Authorization: Bearer wlk_..." \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"limit": 3}}'
```

Waiting, async runs and every local route are on [Desktop local API](https://usewrit.app/docs/local-api).

You can also keep the cloud URL and let your own computer do the work. Link Writ Desktop to your
account, then set the API's **Execution target** on its **Call** tab to **Local agent** (or **Auto (local, else cloud)**). Calls to the published
endpoint then run on your computer, over your own connection, and `X-Writ-Ran-On` says `local`. See [Link Desktop to Writ Cloud](https://usewrit.app/docs/uplink).

## Next

-
- [API keys and OAuth](https://usewrit.app/docs/authentication): Create keys, choose scopes, and rotate or revoke access.
-
- [SDKs](https://usewrit.app/docs/sdks): Python, TypeScript, Go and Rust clients that wait and retry for you.
-
- [Errors and limits](https://usewrit.app/docs/errors): Every error shape, rate limit and plan limit.
-
- [Schedules, triggers and webhooks](https://usewrit.app/docs/automations-webhooks): Run an API on a schedule or when something happens.
