# API reference

Your app's server calls a Feature with one HTTP request. There is no SDK to install. The **Connect** tab of each Feature gives the same information for that exact Feature, as a prompt for your coding assistant: when in doubt, use it.

## The request

```
POST https://featwire.com/api/v1/run
Authorization: Bearer <your FeatWire API key>
Content-Type: application/json
```

The API key starts with `featwire_sk_`. You create it in **API keys**, or in a Feature's **Connect** tab. Keep it in an environment variable on your server, such as `FEATWIRE_API_KEY`, and never in a browser or a mobile app.

## The body

A JSON object:

| Field | Required | What it is |
|---|---|---|
| `feature` | Yes | The name of the Feature, exactly as in the dashboard, such as `"meal-ideas"`. |
| `input` | Yes | What the Feature works on. Its format depends on the kind of Feature: see below. |
| `userId` | No | A stable, non-personal id of the end user the call is made for, such as the user's id in the app's database. Never an email address, a name or a phone number: FeatWire stores it as sent. Leave it out for calls that are not made for a user (background jobs). The daily limit per user set in the FeatWire dashboard counts calls by `userId`: a call without one is never limited. |
| `metadata` | No | A flat object of text, numbers or true/false, recorded with the call. If the app has plans, send the user's plan as `metadata.plan`, for example `{ "plan": "free" }` or `{ "plan": "premium" }`, written the same way every time: the dashboard can then give each plan its own daily limit. Never put personal data in it. |
| `environment` | No | `"production"`, `"staging"` or `"development"`, so that the dashboard can tell the calls apart. Without it, calls are recorded as `"unknown"`. |
| `stream` | No | `true` to get the answer piece by piece. Conversations only. |

Do not send `projectId`: the key already tells FeatWire which project the call belongs to.

Example:

```json
{
  "feature": "meal-ideas",
  "input": "Some text",
  "userId": "user_8f14e45f"
}
```

### Input of a task

A piece of text (a JSON string), from 1 to 10,000 characters, for a Feature created in the dashboard. Send what the user typed, as it is.

### Input of a conversation

A JSON object:

- `messages` (required): the conversation so far, oldest first. Each message is `{ "role": "user" | "assistant", "text": "..." }`, with a text that is not empty. The last message is the user's.
- `context` (optional, text): what the model should know about the user. FeatWire adds it after the Feature's instructions.
- `language` (optional): `"fr"` or `"en"`.

At most 24 messages and 24,000 characters in all the texts and the context together. No other field is accepted. Your app keeps the history: FeatWire does not store it.

```json
{
  "messages": [
    {
      "role": "user",
      "text": "Hi! I would like to start running."
    },
    {
      "role": "assistant",
      "text": "Great idea. How many days a week can you run?"
    },
    {
      "role": "user",
      "text": "Three days, about thirty minutes each."
    }
  ],
  "context": "The user is a beginner and runs on a treadmill.",
  "language": "en"
}
```

## The answer

On success the status is 200 and the body is:

```json
{
  "output": "The model's answer, as plain text.",
  "truncated": false,
  "requestId": "6f1c2e8a-0b7d-4c1e-9a52-3d8f0e4b7c21",
  "feature": {
    "key": "meal-ideas",
    "version": 1
  },
  "model": "gemini-3.5-flash-lite",
  "usage": {
    "inputTokens": 120,
    "outputTokens": 45
  }
}
```

- `output`: the answer. A piece of text for a text Feature; for a structured Feature, a JSON object already checked against its fields.
- `truncated`: `true` when a text answer was cut short by the Feature's maximum answer length. Always `false` for a structured answer: one cut short is an `invalid_output` error instead.
- `requestId` identifies the call. It is also sent in the `X-AIFast-Request-Id` response header, which errors carry too once the call has started. Log it with any error.
- `feature.version`: the version that answered.
- `model`: the model that answered.
- `usage`: the tokens of the call, `inputTokens` and `outputTokens`.

### What is left of a user's daily limit

When the feature has a daily limit per user in the FeatWire dashboard and the call sends a `userId`, the answer carries two response headers, so that the app can show something like "3 messages left today" without another call:

- `X-FeatWire-Quota-Limit`: the user's daily limit for this feature today, the one of their plan (`metadata.plan`) when the plan has its own.
- `X-FeatWire-Quota-Remaining`: the calls the user has left today after this one, never below 0.

They come with the 200 answer, with a streamed answer (before its first event), and with the 429 `quota_exceeded`, where the calls left are 0. A call that failed after it was counted (502 or 504) is given back to the user: its answer carries the headers too, without that call, once FeatWire has confirmed it was given back, and none otherwise.

They are absent when the call has no `userId`, when no limit applies to it (the feature has none, or none for this plan), or when FeatWire could not count the call (it then goes through without a limit). Without them, show no count: never guess one.

Read them on the server, next to the answer, and pass the two numbers on to the app with it (for example as fields of the server function's own response). When `X-FeatWire-Quota-Remaining` is 0, the next call is refused with a 429 `quota_exceeded` until midnight UTC, or until the limit is raised: the app may say so right away, and still handles that 429.

```ts
const limit = response.headers.get("X-FeatWire-Quota-Limit");
const remaining = response.headers.get("X-FeatWire-Quota-Remaining");
// Both null: no limit applies to this call, or it could not be counted. Show no count.
const quota =
  limit !== null && remaining !== null
    ? { limit: Number(limit), remaining: Number(remaining) }
    : null;
```

How to set the limits: [Daily limits per user](/docs/limits#daily-limits-per-user).

## The answer piece by piece

Add `"stream": true` to the body to show a conversation's answer while it is being written. Only conversation Features accept it.

- Anything refused before the answer starts (400, 401, 404, 429, 500, 503) is answered exactly as without `stream`: that status and a JSON error body.
- Otherwise the status is 200, the `Content-Type` is `text/event-stream`, and the `X-AIFast-Request-Id` header carries the request id. The body is a series of server-sent events, each written as `event: <name>`, then `data: <JSON on one line>`, then an empty line:
  - `delta`, data `{ "text": "..." }`: the next piece of the answer, in order. The whole answer is all the pieces put together.
  - `done`, data `{"requestId":"6f1c2e8a-0b7d-4c1e-9a52-3d8f0e4b7c21","feature":{"key":"running-coach","version":1},"model":"gemini-3.5-flash-lite","usage":{"inputTokens":120,"outputTokens":45},"truncated":false}`: the answer is complete. The same fields as the JSON answer, without `output`.
  - `error`, data `{ "error": { "type": "provider_error", "message": "..." } }`: the answer failed after it started, and the stream ends. `type` is `provider_error`, `provider_key_invalid`, `provider_quota_exhausted` or `timeout`; handle it as the 502 or the 504 of the same type.
- Add the answer to the history only after `done`. After `error`, or if the stream ends without `done`, the pieces received are an incomplete answer: discard them and show the friendly error message.
- In a streamed answer the headers are sent before the first event, the call already counted. If the stream then ends with an `error` event, the call is normally given back, so the user usually has one more call left than `X-FeatWire-Quota-Remaining` said; the next answer carries the exact count.
- The Feature's timeout covers the whole answer, from the call to `done`.

What it looks like on the wire:

```
event: delta
data: {"text":"Great! "}

event: delta
data: {"text":"Start with three runs a week."}

event: done
data: {"requestId":"6f1c2e8a-0b7d-4c1e-9a52-3d8f0e4b7c21","feature":{"key":"running-coach","version":1},"model":"gemini-3.5-flash-lite","usage":{"inputTokens":120,"outputTokens":45},"truncated":false}
```

Reading the events in TypeScript, server-side:

```ts
// Server-side only: the key must never reach a browser or a mobile app.
type RunningCoachInput = { messages: { role: "user" | "assistant"; text: string }[]; context?: string; language?: "fr" | "en" };

export async function streamRunningCoach(
  input: RunningCoachInput,
  userId: string,
  onText: (piece: string) => void,
): Promise<string> {
  const response = await fetch("https://featwire.com/api/v1/run", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.FEATWIRE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ feature: "running-coach", input, userId, stream: true }),
    // A little longer than the feature's own limit of 60 seconds, for the whole answer.
    signal: AbortSignal.timeout(65000),
  });
  const requestId = response.headers.get("X-AIFast-Request-Id") ?? "no request id";
  if (!response.ok || !response.body) {
    // Refused before the answer started: a JSON body, as without stream.
    const body = await response.json().catch(() => ({}));
    throw new Error(`FeatWire ${response.status} ${body.error?.type} (${requestId})`);
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  let answer = "";
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }
    buffer += decoder.decode(value, { stream: true });
    // One event per empty line: `event: <name>`, then `data: <JSON>`.
    let end = buffer.indexOf("\n\n");
    while (end !== -1) {
      const block = buffer.slice(0, end);
      buffer = buffer.slice(end + 2);
      end = buffer.indexOf("\n\n");
      const event = /^event: (.*)$/m.exec(block)?.[1];
      const data = JSON.parse(/^data: (.*)$/m.exec(block)?.[1] ?? "null");
      if (event === "delta") {
        answer += data.text;
        onText(data.text);
      } else if (event === "done") {
        return answer;
      } else if (event === "error") {
        // The answer failed after it started: what came so far is incomplete.
        throw new Error(`FeatWire stream ${data.error.type} (${requestId})`);
      }
    }
  }
  throw new Error(`FeatWire stream ended before the answer was complete (${requestId})`);
}
```

## Errors

Every error has a JSON body `{ "error": { "type": "...", "message": "..." } }`. Use the status and `error.type` in your code; `message` is for your logs, not for your users.

| Status | Type | What it means | What to do | Retry? |
|---|---|---|---|---|
| 400 | `invalid_request` | The body or the input is not what the Feature accepts. `message` says what. | Fix the code, or ask the user to change what they entered (a text that is too long, for example). | No |
| 400 | `provider_key_missing` | The project has no AI provider key for the provider this Feature's model uses. Nothing was sent to the AI. | Add the key in the dashboard, page **Settings**. | No |
| 401 | `unauthorized` | The FeatWire API key is missing, wrong or revoked. | Check the key your server sends in `Authorization`. | No |
| 404 | `feature_not_found` | The `feature` name is wrong, or no version of the Feature is live (not published yet, stopped, or archived). | Check the name, then publish a version in the dashboard. | No |
| 429 | `budget_exceeded` | The project reached its monthly spending limit. Nothing was sent to the AI. | Wait for next month, or raise the limit in **Settings**. | No |
| 429 | `quota_exceeded` | This user (`userId`) made as many calls to this Feature today as their daily limit allows. The error also carries `used` and `limit`. | Show the user how many calls are left (`limit - used`). The limit starts again at midnight UTC. | No |
| 500 | `internal_error` | FeatWire is not set up correctly for this Feature. | Report it with the request id. | No |
| 502 | `provider_error` | The AI provider failed. | Try once more. | Once |
| 502 | `invalid_output` | The model answered, but not in the format the Feature declares (or its structured answer was cut short). | Try once more. If it keeps happening, raise the Feature's maximum answer length. | Once |
| 502 | `provider_key_invalid` | The AI provider refused your project's AI provider key: deleted, revoked, or missing a permission. | Replace the key in **Settings**. | No |
| 502 | `provider_quota_exhausted` | Your account at the AI provider has no credit left or reached its spending limit. | Add credit or raise the limit at the provider. | No |
| 503 | `service_unavailable` | FeatWire could not check the key or read the Feature for a moment. | Try once more after a few seconds. | Once, after a few seconds |
| 503 | `provider_key_unavailable` | FeatWire could not read your project's AI provider key for a moment. Nothing was sent to the AI. | Try once more after a few seconds. | Once, after a few seconds |
| 504 | `timeout` | The model did not answer within the Feature's timeout (60 seconds unless you changed it). | Try once more. | Once |

Whatever the error, your app should not crash: show a short, friendly message, and log the status, `error.type` and the request id on the server.

## Timeouts

A Feature waits 60 seconds for the model unless you set its **Timeout** in the dashboard, then answers 504 `timeout`. On your side, give up a little later, after the Feature's timeout plus 5 seconds (65 seconds by default), and handle it like a 504. The examples from **Connect** already do this.

## Examples

With curl:

```bash
curl -sS https://featwire.com/api/v1/run \
  --max-time 65 \
  -H "Authorization: Bearer $FEATWIRE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"feature":"meal-ideas","input":"Some text","userId":"user_8f14e45f"}'
```

With TypeScript, server-side:

```ts
// Server-side only: the key must never reach a browser or a mobile app.
// In a Supabase Edge Function, read it with Deno.env.get("FEATWIRE_API_KEY").
type MealIdeasInput = string;
type MealIdeasOutput = string;

export async function runMealIdeas(
  input: MealIdeasInput,
  userId: string,
): Promise<MealIdeasOutput> {
  const response = await fetch("https://featwire.com/api/v1/run", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.FEATWIRE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ feature: "meal-ideas", input, userId }),
    // A little longer than the feature's own limit of 60 seconds.
    signal: AbortSignal.timeout(65000),
  });
  const body = await response.json();
  if (!response.ok) {
    // body.error.type says what went wrong; log it with the request id.
    throw new Error(
      `FeatWire ${response.status} ${body.error?.type} (${response.headers.get("X-AIFast-Request-Id") ?? "no request id"})`,
    );
  }
  return body.output as MealIdeasOutput;
}
```
