> ## Documentation Index
> Fetch the complete documentation index at: https://docs.neuralfactory.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Your first API call

> Create an API key, get a token, start a run with an agent and read its answer.

By the end of this page a script of yours has asked one of your agents a question through the API and printed the answer.

> [!NOTE]
>
> **Time:** about 10 minutes · **Role:** on Enterprise, an Admin; on SaaS, an Admin or a Member on **Pro** or **Business** · **Works on:** Enterprise and SaaS (not the SaaS **Free** plan) · **You need:** a published agent, `curl` and `jq`, or Python 3 with the `requests` package

## What you will have at the end

* An API key with the **Chat** permission.
* A token made from it.
* A finished run whose answer you read from the API.

The example asks an "HR helper" agent: "How many days of annual leave do new employees get?"

## 1. Create an API key

**1. Open API keys**

In the web app, open **Integrations** › **API keys** in the sidebar and select **Create API Key**.

**2. Fill in the form**

Enter a **Name** such as `hr-helper-script`. Under **Permissions**, keep **Chat** ticked (it is ticked for a new key): it opens `POST /chat` and the run endpoints. Select **Create**.

![The Create New API Key page with hr-helper-script as the name and only the Chat permission ticked.](https://mintcdn.com/neuralfactory/y-MI7aIFykaw0cY2/images/app/api-key-form.png?fit=max\&auto=format\&n=y-MI7aIFykaw0cY2\&q=85\&s=edf4c58e4aac75cb6c0dd1aaf0cb7b22)

**3. Copy the secret**

The **Copy your secret key now** dialog shows the secret once. Copy it, then select **I have saved the key**. Keep the secret out of version control and out of code that runs in a browser.

Put the secret and your agent's id in environment variables. The agent's id is the last part of its address when you open it in **Agents**: `/agents/<agent-id>`.

```bash theme={null}
export NF_API_KEY="<the secret you copied>"
export AGENT_ID="<agent-id>"
export NF_API="https://api.neuralfactory.ai"   # Enterprise: your installation's API address
```

> [!TIP]
>
> You have the secret and an agent id in your shell.

## 2. Get a token

Exchange the secret for a token. The token is valid for 24 hours; after that, exchange the secret again.

```bash curl theme={null}
NF_TOKEN=$(curl -s -X POST "$NF_API/apikeys/token" \
  -H "Content-Type: application/json" \
  -d "{\"key_secret\": \"$NF_API_KEY\"}" | jq -r .access_token)
```

```python Python theme={null}
import os, requests

API = os.environ["NF_API"]
token = requests.post(
    f"{API}/apikeys/token", json={"key_secret": os.environ["NF_API_KEY"]}
).json()["access_token"]
headers = {"Authorization": f"Bearer {token}"}
```

> [!TIP]
>
> `$NF_TOKEN` (or `token`) holds a long string. A `401` here means the secret is wrong or the key is inactive.

## 3. Start a run

Send the message to `POST /chat` as form fields. With `wait=false` the call returns at once with a `202` and a run handle, and the agent works in the background.

```bash curl theme={null}
RUN=$(curl -s -X POST "$NF_API/chat" \
  -H "Authorization: Bearer $NF_TOKEN" \
  -F "agent_id=$AGENT_ID" \
  -F "message=How many days of annual leave do new employees get?" \
  -F "wait=false")
RUN_ID=$(echo "$RUN" | jq -r .run_id)
echo "$RUN"
```

```python Python theme={null}
run = requests.post(
    f"{API}/chat",
    headers=headers,
    data={
        "agent_id": os.environ["AGENT_ID"],
        "message": "How many days of annual leave do new employees get?",
        "wait": "false",
    },
).json()
run_id, chat_id = run["run_id"], run["chat_id"]
```

The handle looks like this:

```json theme={null}
{
  "run_id": "…",
  "chat_id": "…",
  "agent_id": "…",
  "status": "queued",
  "durable": true,
  "stream_url": "/runs/…/stream",
  "interrupts": [],
  "enqueued_followup": null
}
```

> [!TIP]
>
> You have a `run_id`. Keep the `chat_id` too: sending it with your next message continues the same conversation.

## 4. Read the result

Poll `GET /runs/{run_id}` until `status` is no longer `queued` or `running`. When it is `completed`, the agent's answer text is in `result.result`, and `result.documents` lists the sources it used, when it used any.

```bash curl theme={null}
while :; do
  STATUS=$(curl -s "$NF_API/runs/$RUN_ID" -H "Authorization: Bearer $NF_TOKEN" | jq -r .status)
  case "$STATUS" in queued|running) sleep 3 ;; *) break ;; esac
done
curl -s "$NF_API/runs/$RUN_ID" -H "Authorization: Bearer $NF_TOKEN" | jq '{status, answer: .result.result, error}'
```

```python Python theme={null}
import time

while True:
    state = requests.get(f"{API}/runs/{run_id}", headers=headers).json()
    if state["status"] not in ("queued", "running"):
        break
    time.sleep(3)

if state["status"] == "completed":
    print(state["result"]["result"])
else:
    print(state["status"], state.get("error"))
```

> [!TIP]
>
> The answer prints. The run also appears in **Interactions** in the web app, under the key's name.

A status of `awaiting_input` means the agent is waiting for a person, for example with a question. Answer it by sending your reply to `POST /chat` with the same `chat_id`. See [Pauses for a person](https://docs.neuralfactory.ai/api-reference/runs.md#pauses-for-a-person).

## If something goes wrong

| What you see | Why | What to do |
| - | - | - |
| `401` with `Invalid API key credentials` from `/apikeys/token` | The secret is wrong, or the key was deleted | Copy the secret again, or create a new key |
| `401` with `API key is inactive` | The key is turned off, or its creator can no longer act | Turn on **Active Status** on the key's **Edit API Key** page, or create a key as someone who still has access |
| `403` with `API key doesn't have required permissions: …` | The key lacks **Chat** | Add **Chat** to the key's permissions |
| `404` with `Agent not found`, or `403` with `You don't have access to this agent` | The agent id is wrong, or the agent is outside the key's reach | Copy the id again from the agent's address in the web app |
| `403` with `API keys are not available on the Free plan. Upgrade your plan to use them.` | SaaS Free plan | Move to **Pro** or **Business** |
| `409` with `This agent is not published yet` | The agent is a draft | Publish the agent in the web app |
| `429` with `Retry-After` | Too many runs at once | Wait the given seconds. See [Rate and concurrency limits](https://docs.neuralfactory.ai/api-reference/rate-limits.md) |

More codes and messages are on [Errors](https://docs.neuralfactory.ai/api-reference/errors.md).

## Where to go next

* [Runs and results](https://docs.neuralfactory.ai/api-reference/runs.md): wait for the answer in one call, retry safely, cancel.
* [Streaming](https://docs.neuralfactory.ai/api-reference/streaming.md): show the run's progress as it works.
* [Webhooks](https://docs.neuralfactory.ai/api-reference/webhooks.md): get the result pushed to your server instead of polling.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.