> For the complete documentation index, see [llms.txt](https://docs.tagshelf.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tagshelf.dev/quick-start.md). Agents can also search and read this documentation through its [MCP server](https://docs.tagshelf.dev/~gitbook/mcp).

# Quick start

Connect to the Alfred API and extract data from your first document in four steps.

<figure><img src="https://2255375864-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Mae8GCwLSd9I2djPI-M%2Fuploads%2FWeSOvG2qwp25EiRzYB3w%2Fquick-start-paper-plane.png?alt=media&amp;token=90a166e3-4dff-459b-9761-158c771c878c" alt="A first document taking off as a paper plane" width="420"><figcaption></figcaption></figure>

This guide walks you through your first integration with the Alfred API. In about 10 minutes, you'll check your API key, send a document to Alfred (by URL or by uploading it from your computer), wait while Alfred processes it, and read the data Alfred extracted from it.

New to Alfred? [Document processing](https://docs.tagshelf.dev/document-processing.md) explains how a document moves from upload to results.

{% hint style="warning" %}
Before you write any code, confirm the prerequisites below with your Tagshelf Account Manager. Your company's Alfred account is set up by Tagshelf, and the API calls in this guide only work once that setup is complete.
{% endhint %}

### Prerequisites

#### Confirm your account setup with Tagshelf

Your company's account is set up by Tagshelf on the platform side. Contact your assigned Tagshelf Account Manager and confirm that each item below is in place. If you don't know who your Account Manager is, ask your company's Alfred administrator. When an account isn't active, Alfred's error message also includes the Account Manager's name and email address.

| Confirm with your Account Manager                                                                      | Why it matters                                                                                                                                                                                                                                                                                                                                                                       | What you see if it's missing                                                                                                                                                                                                   |
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Your company's account is **active**                                                                   | Alfred refuses every request from an account that is suspended, cancelled or pending payment.                                                                                                                                                                                                                                                                                        | Every request returns `403 Forbidden`, with a message such as `Account is suspended.` and your Account Manager's contact details.                                                                                              |
| Your account's **cloud settings and storage** are configured                                           | Alfred stores your documents and creates jobs only after storage is set up for your company.                                                                                                                                                                                                                                                                                         | Creating jobs or uploading files fails with a message about cloud settings. Registering a webhook returns `409 Conflict`.                                                                                                      |
| You have an **API key** for your integration                                                           | The key identifies your application and the company it belongs to. A key works for one company only. Your Account Manager can tell you which key to use. In the Alfred app, keys are created, rotated and revoked on the **API keys** page. Alfred shows a key's secret only once, when the key is created or rotated.                                                               | Every request returns `401 Unauthorized`.                                                                                                                                                                                      |
| At least one **tag** exists for the documents you'll send, such as *Invoice*, with a clear description | A tag is a document type. Alfred assigns each document to one of your tags, using the tag's description to decide.                                                                                                                                                                                                                                                                   | Alfred can't classify your document, so there's nothing to extract.                                                                                                                                                            |
| The tag has **data points** set to be extracted, such as *Invoice number* and *Total*                  | Data points are the fields Alfred extracts from each document of that tag. They're set up in the Alfred app, not through the API. Without them, Alfred still processes your file. It classifies the file, skips extraction without an error, sends it to review if the tag asks for that, and marks it `finished`. There's just no data to read.                                     | Reading values returns `404 Not Found` with the message `File's tag has no data points set to be extracted.`                                                                                                                   |
| The **file types** you'll send are turned on                                                           | PDFs and images (PNG, JPEG and TIFF) are the easiest place to start; a new account accepts them by default. Alfred also processes CSV, Word (`.docx`) and Excel (`.xlsx`) files. For those, each file type must be turned on for your company, and your account must be set up to process them. Your Account Manager can check both. Older `.doc` and `.xls` files aren't supported. | The request is refused, and the message says the file type isn't enabled for your company.                                                                                                                                     |
| **Review settings** for your tags, if documents need a person to check them                            | A tag can send documents to a person for review before the results are final.                                                                                                                                                                                                                                                                                                        | The file waits in the `confirmation_required` status until someone reviews it in Alfred. The job stays `in_progress`, and its summary shows `has_confirmation_required_files: true` and a `confirmation_required_files_count`. |
| **Cancel, restart and re-extract permissions** for your API key, if your integration needs them        | An API key acts as your company's Account Admin. Cancelling a job, restarting a job and re-extracting a file follow your company's role policy for that role, so your company can deny them. An API key can never reprocess a file.                                                                                                                                                  | The request returns `403 Forbidden` with the message `The requested action is not permitted for this identity and workspace.`                                                                                                  |

{% hint style="info" %}
Keep your API key secret. Store it in an environment variable or a secrets manager, never in your code or in a repository. If a key is exposed, ask for it to be revoked. A revoked key stops working immediately.
{% endhint %}

#### Prepare your environment

Once your account is confirmed, you need:

| What                                         | Details                                                                                                                                                                                                                                                          |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Your API key, in an environment variable     | The examples read it from `ALFRED_API_KEY`. On macOS or Linux, run `export ALFRED_API_KEY="<your API key>"`.                                                                                                                                                     |
| Network access to `https://app.tagshelf.com` | Every API request goes to this host over HTTPS.                                                                                                                                                                                                                  |
| A document to send                           | A file at a URL that Alfred can download, or a file on your computer. It should match one of your tags. PDFs and images are the easiest place to start. CSV, Word (`.docx`) and Excel (`.xlsx`) files work too, once those types are turned on for your company. |
| Python 3 with `requests`, or cURL            | The examples use both. Install the Python library with `pip install requests`.                                                                                                                                                                                   |

Every request also needs a `User-Agent` header that identifies your integration, such as `my-integration/1.0`. Requests without it return `403 Forbidden`. The [API conventions](https://docs.tagshelf.dev/endpoints/api-conventions.md) page explains the headers, response format, errors and rate limits that apply to every endpoint.

### How it works

The whole flow takes four steps:

1. **Check your credentials** with `GET /api/tagshelf/ping`.
2. **Send a document**, either by URL with `POST /api/file/upload`, or by uploading files from your computer with a deferred session. Either way, Alfred creates a job.
3. **Wait for the job to finish** by polling `GET /api/job/detail/{id}`, then read the job's files once with `view=full`.
4. **Read the extracted data** with `GET /api/values/file/{id}`.

The Python examples share these settings. Run them once at the start of your script or Python session:

```python
import os
import requests

BASE_URL = "https://app.tagshelf.com"
HEADERS = {
    "X-TagshelfAPI-Key": os.environ["ALFRED_API_KEY"],
    "User-Agent": "my-integration/1.0",
}
```

### Step 1: Check your credentials

Call `GET /api/tagshelf/ping` to confirm that Alfred accepts your API key. It's the quickest way to rule out setup problems before you send real documents.

{% tabs %}
{% tab title="cURL" %}

```bash
curl "https://app.tagshelf.com/api/tagshelf/ping" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0"
```

{% endtab %}

{% tab title="Python" %}

```python
response = requests.get(f"{BASE_URL}/api/tagshelf/ping", headers=HEADERS)
response.raise_for_status()
print(response.json())
```

{% endtab %}
{% endtabs %}

If your key works, Alfred responds with `200 OK` and the name of the application the key belongs to:

```json
{
  "pong": "my-integration-app"
}
```

To confirm that the key belongs to the company you expect, call [`GET /api/tagshelf/who-am-i`](https://docs.tagshelf.dev/endpoints/tagshelf.md). Its response includes your `company_name`.

### Step 2: Send your first document

There are two ways to send documents to Alfred. Choose the one that matches where your files are:

| Your files are…            | Use                                            | Calls |
| -------------------------- | ---------------------------------------------- | ----- |
| At a URL Alfred can reach  | Option A: Send a document by URL               | One   |
| On your computer or server | Option B: Upload files with a deferred session | Three |

Both options end with a `job_id`, which you use in Step 3.

#### Option A: Send a document by URL

Give Alfred the URL of your document with `POST /api/file/upload`. Alfred downloads the file, creates a job for it and starts processing right away. Replace the example URL with your own document.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://app.tagshelf.com/api/file/upload" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://files.example.com/invoices/invoice-1042.pdf",
    "correlation_id": "erp:invoice:INV-1042",
    "metadata": { "customer": "ACME" }
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
response = requests.post(
    f"{BASE_URL}/api/file/upload",
    headers=HEADERS,
    json={
        "url": "https://files.example.com/invoices/invoice-1042.pdf",
        "correlation_id": "erp:invoice:INV-1042",
        "metadata": {"customer": "ACME"},
    },
)
response.raise_for_status()
job_id = response.json()["job_id"]
print("Job created:", job_id)
```

{% endtab %}
{% endtabs %}

Alfred responds with `202 Accepted`, the ID of the new job and the correlation ID you sent. Keep the `job_id` for Step 3.

```json
{
  "job_id": "7a1d5c3e-9b2f-4e8a-8c61-3f2b9d0e4a17",
  "correlation_id": "erp:invoice:INV-1042"
}
```

Two optional fields link the job to your own systems:

| Field            | What it does                                                                                                                                                                                                                                                                                                                                  |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `correlation_id` | Your own ID for the operation behind this job, such as an invoice or order number, up to 512 characters. Alfred saves it exactly as you sent it and returns it in the job's details and events. Several jobs can share one, and Alfred never uses it to remove duplicates. If you don't send one, the response has an empty `correlation_id`. |
| `metadata`       | Your own data for the file, such as a customer name. Alfred stores it with the file and returns it later.                                                                                                                                                                                                                                     |

To find every job you sent for one operation, call `GET /api/job/all?correlation_id=erp:invoice:INV-1042` (URL-encode the value). The match is exact and case-sensitive. See [Job](https://docs.tagshelf.dev/endpoints/job.md).

#### Option B: Upload files with a deferred session

A deferred session holds the files you upload until you're ready to process them together as one job. It takes three calls: open a session, upload each file to it, then submit the session as a job. Each upload request can be up to 250 MB. Your company also has a largest-file setting (1 GB unless your company changed it) that applies to every way of sending files, including URLs.

**1. Open a session.** `POST /api/deferred/create` takes no request body and returns a `session_id`.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://app.tagshelf.com/api/deferred/create" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0"
```

{% endtab %}

{% tab title="Python" %}

```python
response = requests.post(f"{BASE_URL}/api/deferred/create", headers=HEADERS)
response.raise_for_status()
session_id = response.json()["session_id"]
print("Session opened:", session_id)
```

{% endtab %}
{% endtabs %}

```json
{
  "session_id": "0f767925-b464-4ffa-b621-1a0aeacac256"
}
```

**2. Upload each file to the session.** Send each file to `POST /api/file/uploadfile` as `multipart/form-data`, with the `session_id` as a form field. Repeat this call for every file you want in the job.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://app.tagshelf.com/api/file/uploadfile" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0" \
  -F "file=@invoice-1042.pdf;type=application/pdf" \
  -F "session_id=0f767925-b464-4ffa-b621-1a0aeacac256"
```

{% endtab %}

{% tab title="Python" %}

```python
with open("invoice-1042.pdf", "rb") as file:
    response = requests.post(
        f"{BASE_URL}/api/file/uploadfile",
        headers=HEADERS,
        files={"file": ("invoice-1042.pdf", file, "application/pdf")},
        data={"session_id": session_id},
    )
response.raise_for_status()
print("Uploaded file:", response.json()["file_id"])
```

{% endtab %}
{% endtabs %}

```json
{
  "file_id": "559167cb-4c76-4e28-bf15-34cbf614119c"
}
```

Send each file with its real content type, such as `application/pdf` for a PDF or `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` for an Excel file. Alfred uses it to recognize the file. A file over the size limits gets `413 Payload Too Large`, with the limit in `max_bytes`.

**3. Submit the session as a job.** When all your files are uploaded, send the `session_id` to `POST /api/job/create`, with an optional `correlation_id`. Alfred starts processing, and the session closes. Open a new session for your next batch.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://app.tagshelf.com/api/job/create" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0" \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "0f767925-b464-4ffa-b621-1a0aeacac256",
    "correlation_id": "erp:invoice:INV-1042"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
response = requests.post(
    f"{BASE_URL}/api/job/create",
    headers=HEADERS,
    json={"session_id": session_id, "correlation_id": "erp:invoice:INV-1042"},
)
response.raise_for_status()
job_id = response.json()["job_id"]
print("Job created:", job_id)
```

{% endtab %}
{% endtabs %}

Alfred responds with `202 Accepted`, the ID of the new job and the correlation ID you sent. Keep the `job_id` for Step 3.

```json
{
  "job_id": "7a1d5c3e-9b2f-4e8a-8c61-3f2b9d0e4a17",
  "correlation_id": "erp:invoice:INV-1042"
}
```

{% hint style="info" %}
Sessions expire if they're left open too long. If an upload is rejected because the session is closed or expired, open a new session and upload the files again. The [Deferred Session](https://docs.tagshelf.dev/endpoints/deferred-session.md) page covers the other options, such as attaching metadata to each file.
{% endhint %}

### Step 3: Wait for the job to finish

Alfred processes documents in the background, so the job isn't finished when the upload returns. Check it with `GET /api/job/detail/{id}` every few seconds and look at its `stage`. By default this call returns the job's summary: its `stage`, file counts and dates. That is all you need to wait. A read can be up to five seconds old, so polling more often than every five seconds gains nothing.

{% tabs %}
{% tab title="cURL" %}

```bash
curl "https://app.tagshelf.com/api/job/detail/7a1d5c3e-9b2f-4e8a-8c61-3f2b9d0e4a17" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0"
```

{% endtab %}

{% tab title="Python" %}

```python
import time

DONE = {"completed"}
ENDED_WITHOUT_RESULTS = {"failed", "invalid", "canceled", "expired"}

while True:
    response = requests.get(f"{BASE_URL}/api/job/detail/{job_id}", headers=HEADERS)
    response.raise_for_status()
    job = response.json()
    print("Stage:", job["stage"])
    if job["stage"] in DONE | ENDED_WITHOUT_RESULTS:
        break
    time.sleep(5)
```

{% endtab %}
{% endtabs %}

The job is done when its `stage` is `completed`. If the stage is `failed`, `invalid`, `canceled` or `expired`, the job ended without results. A job with a file that is waiting for a person to review it stays in `in_progress`, so it is not done yet. Its summary shows `has_confirmation_required_files` and `confirmation_required_files_count`. Every stage is described in [Job Stages](https://docs.tagshelf.dev/endpoints/job/job-stages.md).

When the job is done, read its files once. The summary has no `files` list, so ask for the full view with `view=full`. An API key may do this, and so may your company's Account Admin. The `exclude` parameter leaves out the parts you don't need, which keeps the response small.

{% tabs %}
{% tab title="cURL" %}

```bash
curl "https://app.tagshelf.com/api/job/detail/7a1d5c3e-9b2f-4e8a-8c61-3f2b9d0e4a17?view=full&exclude=metadata,fileUrls,errorMessages" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0"
```

{% endtab %}

{% tab title="Python" %}

```python
response = requests.get(
    f"{BASE_URL}/api/job/detail/{job_id}",
    headers=HEADERS,
    params={"view": "full", "exclude": "metadata,fileUrls,errorMessages"},
)
response.raise_for_status()
files = response.json()["files"]
file_ids = [file["id"] for file in files]
```

{% endtab %}
{% endtabs %}

Each item in `files` has the file's `id`, `file_name` and `status`. Keep the file IDs for the next step.

{% hint style="warning" %}
**Changed in v1.130.0.** `GET /api/job/detail/{id}` returns the job summary by default, and the summary has no `files` list. If your integration reads `files`, `metadata` or `file_urls` from this call, add `view=full`. The full view is allowed for API keys and Account Admins. Anyone else who asks for it gets `403 Forbidden`.
{% endhint %}

{% hint style="info" %}
In production, you can have Alfred notify you when a job changes instead of checking repeatedly. See the [Event API](https://docs.tagshelf.dev/event-api.md).
{% endhint %}

### Step 4: Read the extracted data

For each file, call `GET /api/values/file/{id}` to get the values Alfred extracted, such as the invoice number and total.

{% tabs %}
{% tab title="cURL" %}

```bash
curl "https://app.tagshelf.com/api/values/file/559167cb-4c76-4e28-bf15-34cbf614119c" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0"
```

{% endtab %}

{% tab title="Python" %}

```python
for file_id in file_ids:
    response = requests.get(f"{BASE_URL}/api/values/file/{file_id}", headers=HEADERS)
    if response.status_code in (204, 404):
        print(file_id, "has no extracted values")
        continue
    response.raise_for_status()
    values = {value["field_key"]: value["value"] for value in response.json()}
    print(file_id, values)
```

{% endtab %}
{% endtabs %}

Alfred returns one item for each value. This example shows two values from an invoice:

```json
[
  {
    "id": "b7e2c4a1-3f5d-4e8b-9a6c-1d2e3f4a5b6c",
    "file_log_id": "4b2a9c8d-1e7f-4a3b-9c5d-6e7f8a9b0c1d",
    "metadata_id": "d1e2f3a4-b5c6-4d7e-8f90-a1b2c3d4e5f6",
    "metadata_name": "Invoice number",
    "field_key": "invoice_number",
    "value": "INV-1042",
    "classification_score": 0.99
  },
  {
    "id": "f1a2b3c4-d5e6-4f7a-8b9c-0d1e2f3a4b5c",
    "file_log_id": "4b2a9c8d-1e7f-4a3b-9c5d-6e7f8a9b0c1d",
    "metadata_id": "e2f3a4b5-c6d7-4e8f-90a1-b2c3d4e5f6a7",
    "metadata_name": "Total",
    "field_key": "total",
    "value": "390.00",
    "classification_score": 0.98,
    "extracted_value": "$390",
    "normalized_value": "390.00"
  }
]
```

These are the fields you'll use most:

| Field                  | What it tells you                                                                                                                                                                            |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `field_key`            | A stable name for the data point. Map your own fields to it. Unlike `metadata_name`, it doesn't change if someone renames the data point.                                                    |
| `value`                | The final value, after Alfred applied the tag's formatting rules.                                                                                                                            |
| `classification_score` | How confident Alfred is, from 0 to 1. A higher score means Alfred is more confident. It doesn't tell you whether the result is correct, so check low-scoring values before you rely on them. |
| `extracted_value`      | What Alfred originally read, when formatting changed it. In this example, `$390` became `390.00`.                                                                                            |

If the file's tag has no data points, Alfred still processes the file, but this call returns `404 Not Found` because there are no values to read. Every field is described in [Values](https://docs.tagshelf.dev/endpoints/values.md).

### Complete script

This script runs all four steps in order. Save it as `alfred_quickstart.py` and set what to send: put your document's URL in `DOCUMENT_URL`, or list files on your computer in `LOCAL_FILES` to upload them with a deferred session. Then run `python alfred_quickstart.py`. The script stops with a message if the job ends without results or takes longer than 15 minutes.

```python
"""Send documents to Alfred, wait for them to be processed, and print the extracted values."""

import mimetypes
import os
import sys
import time

import requests

BASE_URL = "https://app.tagshelf.com"
HEADERS = {
    "X-TagshelfAPI-Key": os.environ["ALFRED_API_KEY"],
    "User-Agent": "my-integration/1.0",
}

# Send a document by URL...
DOCUMENT_URL = "https://files.example.com/invoices/invoice-1042.pdf"
# ...or list files on your computer to upload them with a deferred session instead.
LOCAL_FILES = []  # for example: ["invoice-1042.pdf", "invoice-1043.pdf"]

DONE = {"completed"}
ENDED_WITHOUT_RESULTS = {"failed", "invalid", "canceled", "expired"}
POLL_SECONDS = 5
TIMEOUT_SECONDS = 15 * 60


def check_credentials():
    response = requests.get(f"{BASE_URL}/api/tagshelf/ping", headers=HEADERS)
    response.raise_for_status()
    print("Authenticated as:", response.json()["pong"])


def send_document(url):
    response = requests.post(
        f"{BASE_URL}/api/file/upload",
        headers=HEADERS,
        json={"url": url},
    )
    response.raise_for_status()
    job_id = response.json()["job_id"]
    print("Job created:", job_id)
    return job_id


def send_local_files(paths):
    response = requests.post(f"{BASE_URL}/api/deferred/create", headers=HEADERS)
    response.raise_for_status()
    session_id = response.json()["session_id"]
    print("Session opened:", session_id)

    for path in paths:
        content_type = mimetypes.guess_type(path)[0] or "application/octet-stream"
        with open(path, "rb") as file:
            response = requests.post(
                f"{BASE_URL}/api/file/uploadfile",
                headers=HEADERS,
                files={"file": (os.path.basename(path), file, content_type)},
                data={"session_id": session_id},
            )
        response.raise_for_status()
        print("Uploaded:", path)

    response = requests.post(
        f"{BASE_URL}/api/job/create",
        headers=HEADERS,
        json={"session_id": session_id},
    )
    response.raise_for_status()
    job_id = response.json()["job_id"]
    print("Job created:", job_id)
    return job_id


def wait_for_job(job_id):
    """Poll the job summary until the job reaches a final stage."""
    deadline = time.monotonic() + TIMEOUT_SECONDS
    while time.monotonic() < deadline:
        response = requests.get(f"{BASE_URL}/api/job/detail/{job_id}", headers=HEADERS)
        response.raise_for_status()
        stage = response.json()["stage"]
        print("Stage:", stage)
        if stage in DONE | ENDED_WITHOUT_RESULTS:
            return stage
        time.sleep(POLL_SECONDS)
    sys.exit(f"Job {job_id} didn't finish within {TIMEOUT_SECONDS // 60} minutes.")


def get_files(job_id):
    """Read the job's files once, with the full view."""
    response = requests.get(
        f"{BASE_URL}/api/job/detail/{job_id}",
        headers=HEADERS,
        params={"view": "full", "exclude": "metadata,fileUrls,errorMessages"},
    )
    response.raise_for_status()
    return response.json()["files"]


def print_values(file_id):
    response = requests.get(f"{BASE_URL}/api/values/file/{file_id}", headers=HEADERS)
    if response.status_code in (204, 404):
        print("  No extracted values for this file.")
        return
    response.raise_for_status()
    for value in response.json():
        print(f"  {value['field_key']}: {value['value']}")


def main():
    check_credentials()
    if LOCAL_FILES:
        job_id = send_local_files(LOCAL_FILES)
    else:
        job_id = send_document(DOCUMENT_URL)
    stage = wait_for_job(job_id)
    if stage in ENDED_WITHOUT_RESULTS:
        sys.exit(f"Job ended without results (stage: {stage}).")
    for file in get_files(job_id):
        print(f"{file['file_name']} ({file['status']}):")
        print_values(file["id"])


if __name__ == "__main__":
    main()
```

A successful run prints something like this:

```
Authenticated as: my-integration-app
Job created: 7a1d5c3e-9b2f-4e8a-8c61-3f2b9d0e4a17
Stage: queued
Stage: in_progress
Stage: completed
invoice-1042.pdf (finished):
  invoice_number: INV-1042
  total: 390.00
```

### Troubleshooting

| What you see                                                                                           | Likely cause                                                                                                                                                                                                                     | What to do                                                                                                                                      |
| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `401 Unauthorized` on every request                                                                    | The API key is missing, mistyped or revoked.                                                                                                                                                                                     | Check that `ALFRED_API_KEY` is set in the terminal you run the script from. If it is, ask your Account Manager whether the key is still active. |
| `403 Forbidden` with `Account is suspended.`, `Account is cancelled.` or `Account is pending payment.` | Your company's account isn't active.                                                                                                                                                                                             | Contact the Account Manager named in the message.                                                                                               |
| `403 Forbidden` on every request, with no account message                                              | The `User-Agent` header is missing.                                                                                                                                                                                              | Add a `User-Agent` header to every request.                                                                                                     |
| Upload fails and the message mentions cloud settings                                                   | Your account's storage isn't set up.                                                                                                                                                                                             | Ask your Account Manager to finish setting up your account.                                                                                     |
| `400 Bad Request` when sending by URL                                                                  | The request has no source, mixes `url` or `urls` with a remote `source`, lists more than 100 URLs, has a `correlation_id` that isn't a string or is longer than 512 characters, or the file type isn't enabled for your company. | Send `url`, `urls` or `source`, and read the `message` in the response.                                                                         |
| The job ends in `invalid` or `failed`                                                                  | Alfred couldn't download the file.                                                                                                                                                                                               | Open the URL from a machine outside your network. It must work without signing in, and your server should send an accurate `Content-Type`.      |
| A CSV, Word or Excel file is refused                                                                   | The file type isn't turned on for your company, or your account isn't set up to process it.                                                                                                                                      | Ask your Account Manager to turn on the file types you need and to check that your account can process them.                                    |
| `413 Payload Too Large` when uploading a file                                                          | The upload is over the 250 MB request limit or your company's largest-file setting.                                                                                                                                              | Send a smaller file. The `max_bytes` field in the response shows the limit that applied.                                                        |
| The job stays in `in_progress`, and its summary shows `has_confirmation_required_files: true`          | A file is waiting for a person to review it (status `confirmation_required`).                                                                                                                                                    | Someone reviews it in the Alfred app, or your Account Manager adjusts the tag's review settings.                                                |
| `404 Not Found` when reading values, with `File's tag has no data points set to be extracted.`         | The file was processed, but its tag has no data points.                                                                                                                                                                          | Ask your Account Manager or Alfred administrator to set up data points for the tag, then reprocess the file.                                    |
| `400 Bad Request` when uploading to a session                                                          | The session is closed or expired, or the file field is missing.                                                                                                                                                                  | Open a new session with `POST /api/deferred/create` and upload the files again.                                                                 |
| `KeyError: 'files'` when reading a job                                                                 | Since v1.130.0, the job detail returns the summary unless you ask for `view=full`.                                                                                                                                               | Add `view=full` to the request, as in Step 3.                                                                                                   |
| `429 Too Many Requests`                                                                                | You went over 2,500 requests per minute to one endpoint.                                                                                                                                                                         | Wait the number of seconds in the `Retry-After` header, and space out your status checks.                                                       |

Error responses can include their own `correlation_id`, a short code that Alfred generates for that error. It's different from the correlation ID you send with a job. If you contact support about an error, include that code, the endpoint you called, the time of the request and the `message` from the response. It helps the team find your request.

### Next steps

| If you want to…                                                    | Read                                                                                                                                |
| ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| Understand how a document moves through Alfred                     | [Document processing](https://docs.tagshelf.dev/document-processing.md)                                                             |
| Check a session's status, or attach metadata to each uploaded file | [Deferred Session](https://docs.tagshelf.dev/endpoints/deferred-session.md) and [File](https://docs.tagshelf.dev/endpoints/file.md) |
| Read files straight from Amazon S3, Azure or DigitalOcean          | [Remote Sources](https://docs.tagshelf.dev/endpoints/file/source.md)                                                                |
| Find every job that shares one of your correlation IDs             | [Job](https://docs.tagshelf.dev/endpoints/job.md)                                                                                   |
| Get notified when a job finishes, instead of checking              | [Event API](https://docs.tagshelf.dev/event-api.md) and [Account](https://docs.tagshelf.dev/endpoints/account.md)                   |
| See which data points a tag extracts                               | [Tag](https://docs.tagshelf.dev/endpoints/tag.md) and [Metadata](https://docs.tagshelf.dev/endpoints/metadata.md)                   |
| Export every confirmed value for a tag, page by page               | [Report](https://docs.tagshelf.dev/endpoints/report.md)                                                                             |
| Find documents by their extracted data                             | [Search](https://docs.tagshelf.dev/endpoints/search.md)                                                                             |
| Understand every file status                                       | [File Status](https://docs.tagshelf.dev/endpoints/file/file-status.md)                                                              |
| Choose between API keys, OAuth and HMAC                            | [Authentication](https://docs.tagshelf.dev/authentication.md)                                                                       |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.tagshelf.dev/quick-start.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
