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

# Automate invoice intake with Box AI Extract

When a PDF is uploaded to a designated Box folder, this service extracts the vendor name, invoice number, dates, total, and currency with Box AI, then writes those values back to the file as metadata.

## Before you start

Complete these Box setup steps before you build. You need:

* A free Box developer account, or a Box Enterprise account with **Box AI** enabled.
* A Box application configured with **Client Credentials Grant** authentication, authorized in the Admin Console, with these scopes:
  * Read and write all files and folders stored in Box
  * Manage AI
  * Manage webhooks
* A runtime for the stack you choose: Python 3.11+, Node.js 20+, Java 17+, or .NET 8+.
* For the agent path, a coding agent such as Codex, Claude Code, or Cursor. Installing Box Agent Skills helps it use current Box APIs.

Keep the metadata template key, inbox folder ID, and enterprise ID handy. The prompt and your `.env` file need them.

> [accordion] 1. Create the metadata template
>
> The metadata template defines the fields Box AI extracts. Create it once, and every invoice processed by the service returns values in this shape.
>
> > [!TIP]
> >
> > This step requires Admin access. If you do not have access, contact your Box administrator.
>
> 1. Open the [Box Admin Console](https://app.box.com/master) and select **Metadata**.
> 2. In the **Invoices** tab, select **New** and name it `Invoice`.
> 3. Add the following fields:
>
> | Field name | Type | Description |
> | - | - | - |
> | Vendor Name | Text | The name of the vendor or supplier issuing the invoice |
> | Invoice Number | Text | The unique invoice identifier |
> | Invoice Date | Date | The date the invoice was issued |
> | Due Date | Date | The payment due date |
> | Total Amount | Number | The total amount due, including taxes and fees |
> | Currency | Text | The three-letter currency code (for example, USD, EUR, GBP) |
>
> 4. Copy the template key from under the **Template Name**. You need it for the prompt and for `.env`.
> 5. Select **Save**.
>
> For a detailed walkthrough, see Customizing Metadata Templates.

> [accordion] 2. Create the invoices inbox folder
>
> Create a dedicated folder in Box to serve as the invoice drop zone.
>
> 1. In Box, create a new folder called `Invoices Inbox`.
>
> 2. Note the **folder ID** from the URL. For example, if the URL is `https://app.box.com/folder/123456789`, the folder ID is `123456789`.
>
> 3. **Share the folder with your application's service account.** This is required because CCG applications act as a separate service account user that does not automatically have access to your content.
>
> > [!WARNING]
> >
> > **This step is critical.** Without it, all API calls return 404 "Not found" errors.
> >
> > To find your service account email: go to the [Developer Console](https://app.box.com/developers/console), open your app, select the **Configuration** tab, and look in the **App Details** sidebar for the **Service Account ID** (it looks like `AutomationUser_xxxxx_xxxxxx@boxdevedition.com`).
> >
> > Invite this email as a **collaborator** on the folder with the **Editor** role. Editor access is required because the app needs to write metadata back to files.

## Build with an agent

Gather these values from [Before you start](#before-you-start):

* **Metadata template key** - from the template you created
* **Invoices Inbox folder ID** - from the folder URL
* **Enterprise ID** - from the [Developer Console](https://app.box.com/developers/console), using the icon in the top-right

Choose your stack and copy the prompt. It already lists these as prerequisites, so the agent reads them from environment variables instead of trying to create them. Replace the `<TEMPLATE_KEY>`, `<FOLDER_ID>`, and `<ENTERPRISE_ID>` placeholders if you want the agent to pre-fill `.env`; otherwise leave them and fill `.env` yourself after scaffolding.

```md Python + Flask theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use Python with Flask. Target Python 3.11+, use pip and a virtual environment. Install exactly one Box package: "boxsdk~=10.0" (do NOT also install box-sdk-gen — both ship the box_sdk_gen module and conflict). Import Box APIs with `from box_sdk_gen import ...`. Also install flask, python-dotenv, and pytest for tests.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

Mirror the Python tab in the tutorial for Box client, extract, and metadata modules. Use Flask for the webhook server exactly as in the Build by hand path.

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- box_client.py, extract.py, metadata.py, and app.py (POST /webhook) matching the tutorial modules
- a flat Flask layout matching the tutorial (no unnecessary packages)
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Python + FastAPI theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use Python with FastAPI. Target Python 3.11+, use pip and a virtual environment. Install exactly one Box package: "boxsdk~=10.0" (do NOT also install box-sdk-gen — both ship the box_sdk_gen module and conflict). Import Box APIs with `from box_sdk_gen import ...`. Also install fastapi, uvicorn, python-dotenv, and pytest for tests.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

The tutorial's Python samples use Flask. Copy the Box client, extract, and metadata modules from those samples unchanged. Adapt only the HTTP layer to FastAPI + uvicorn. The Box Python SDK is synchronous — use plain def route handlers (or run sync Box calls in a threadpool); do not await sync SDK methods.

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- box_client.py, extract.py, metadata.py (same Box logic as the tutorial), and a FastAPI app module with POST /webhook
- an idiomatic FastAPI layout; keep Box modules separate from the HTTP layer
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md TypeScript + Express theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use TypeScript with Express on Node.js 20+. Use npm, box-node-sdk@10 (BoxClient, BoxCcgAuth, CcgConfig, BoxApiError from box-node-sdk; AiItemBase from box-node-sdk/schemas/aiItemBase), express, dotenv, tsx (or tsc), and a test runner such as node:test or vitest.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

Mirror the TypeScript tab in the tutorial for Box client, extract, metadata, and Express webhook server. Use commonjs-friendly tsconfig (module commonjs, moduleResolution node, esModuleInterop, strict) and run with npx tsx app.ts.

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- boxClient.ts, extract.ts, metadata.ts, and app.ts (POST /webhook) mirroring the tutorial modules
- a flat Express + TypeScript layout matching the tutorial
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md TypeScript + Fastify theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use TypeScript with Fastify on Node.js 20+. Use npm, box-node-sdk@10 (BoxClient, BoxCcgAuth, CcgConfig, BoxApiError from box-node-sdk; AiItemBase from box-node-sdk/schemas/aiItemBase), fastify, dotenv, tsx (or tsc), and a test runner such as node:test or vitest.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

The tutorial's TypeScript samples use Express. Copy the Box client, extract, and metadata modules from those samples unchanged. Adapt only the HTTP layer to Fastify. Register a JSON body parser / use Fastify's default JSON content-type handling so POST /webhook receives parsed JSON. Keep listen on port 5000 for the local curl test.

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- boxClient.ts, extract.ts, metadata.ts (same Box logic as the tutorial), and a Fastify app module with POST /webhook
- an idiomatic Fastify + TypeScript layout; keep Box modules separate from the HTTP layer
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Node + Express theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use Node.js 20+ with JavaScript (not TypeScript) and Express. Use npm and exactly one Box package: box-node-sdk@10 (do NOT also install box-typescript-sdk-gen). Import BoxClient, BoxCcgAuth, CcgConfig, and BoxApiError from box-node-sdk, and AiItemBase from box-node-sdk/schemas/aiItemBase. Also install express, dotenv, and a test runner such as node:test.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

The tutorial's Build by hand samples are Python and TypeScript. Use those as the behavioral spec for Box client, extract, metadata, 409 metadata upsert, and webhook handling. Adapt the HTTP layer to Express in JavaScript. Keep listen on port 5000 for the local curl test.

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- boxClient.js, extract.js, metadata.js, and app.js (POST /webhook)
- a flat Express + JavaScript layout; keep Box modules separate from the HTTP layer
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Node + NestJS theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use Node.js 20+ with NestJS. NestJS projects use TypeScript by default. Use npm and exactly one Box package: box-node-sdk@10 (do NOT also install box-typescript-sdk-gen). Import BoxClient, BoxCcgAuth, CcgConfig, and BoxApiError from box-node-sdk, and AiItemBase from box-node-sdk/schemas/aiItemBase. Also install @nestjs/core, @nestjs/common, @nestjs/platform-express, dotenv, and a test runner such as Jest.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

The tutorial's Build by hand samples are Python and TypeScript Express. Use those as the behavioral spec for Box client, extract, metadata, 409 metadata upsert, and webhook handling. Adapt only the HTTP layer to NestJS. Enable JSON body parsing (NestJS default with the Express adapter). NestJS POST handlers return 201 by default — set @HttpCode(200) on POST /webhook so the local curl test sees 200. For the AiItemBase import from box-node-sdk/schemas/aiItemBase, TypeScript moduleResolution node cannot resolve the SDK package export; use bundler or Node16 so nest build and Jest succeed. Keep listen on port 5000 for the local curl test.

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- a Box client provider, extract provider, metadata provider, and a webhook controller with POST /webhook
- an idiomatic NestJS layout (module, controller, providers); keep Box client, extract, and metadata in dedicated providers separate from the HTTP controller
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Java + Spring Boot theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use Java 17+ with Spring Boot 3. Use Maven or Gradle and exactly one Box artifact: com.box:box-java-sdk version 10 or later (do NOT also add box-java-sdk-gen). Use BoxClient, BoxCCGAuth, CCGConfig, BoxAPIError, and the generated AI/metadata types from that SDK (packages under com.box.sdkgen). Also use spring-boot-starter-web and a test starter such as spring-boot-starter-test.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

The tutorial's Build by hand samples are Python and TypeScript. Use those as the behavioral spec for CCG enterprise auth, extract_structured with the metadata template (not inline fields), 409 metadata upsert with JSON-Patch op add, and webhook handling. Adapt the HTTP layer to Spring Web (@RestController). Call client.getAi().createAiExtractStructured(...) with an AiExtractStructured.Builder request whose metadataTemplate is an AiExtractStructuredMetadataTemplateField (templateKey + type METADATA_TEMPLATE + scope "enterprise") — not the Python CreateAiExtractStructuredMetadataTemplate name. On 409, catch BoxAPIError and check getResponseInfo().getStatusCode(). For JSON-Patch updates, UpdateFileMetadataByIdRequestBody.Builder.value(...) accepts only String, long, double, List<String>, or MetadataInstanceValue — convert extracted Object values (for example totalAmount) to those overloads; do not pass Object. Keep the server on port 5000 for the local curl test (server.port=5000).

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- a Box client configuration/bean, ExtractService, MetadataService, and a webhook controller with POST /webhook
- an idiomatic Spring Boot layout; keep Box client configuration, extract, and metadata in dedicated classes separate from the HTTP controller
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Java + Quarkus theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use Java 17+ with Quarkus. Use Maven or Gradle and exactly one Box artifact: com.box:box-java-sdk version 10 or later (do NOT also add box-java-sdk-gen). Use BoxClient, BoxCCGAuth, CCGConfig, BoxAPIError, and the generated AI/metadata types from that SDK (packages under com.box.sdkgen). Also use quarkus-rest-jackson (or quarkus-resteasy-jackson) and quarkus-junit5 for tests.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

The tutorial's Build by hand samples are Python and TypeScript. Use those as the behavioral spec for CCG enterprise auth, extract_structured with the metadata template (not inline fields), 409 metadata upsert with JSON-Patch op add, and webhook handling. Adapt the HTTP layer to Quarkus REST. Call client.getAi().createAiExtractStructured(...) with an AiExtractStructured.Builder request whose metadataTemplate is an AiExtractStructuredMetadataTemplateField (templateKey + type METADATA_TEMPLATE + scope "enterprise") — not the Python CreateAiExtractStructuredMetadataTemplate name. On 409, catch BoxAPIError and check getResponseInfo().getStatusCode(). For JSON-Patch updates, UpdateFileMetadataByIdRequestBody.Builder.value(...) accepts only String, long, double, List<String>, or MetadataInstanceValue — convert extracted Object values (for example totalAmount) to those overloads; do not pass Object. Keep the server on port 5000 for the local curl test (quarkus.http.port=5000).

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- a Box client producer/bean, ExtractService, MetadataService, and a JAX-RS resource with POST /webhook
- an idiomatic Quarkus layout; keep Box client, extract, and metadata in dedicated beans/classes separate from the JAX-RS resource
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md .NET + ASP.NET Core theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use .NET 8+ with ASP.NET Core controllers. Use NuGet and exactly one Box package: Box.V2.Core version 10 or later (do NOT also install Box.Sdk.Gen — v10 of Box.V2.Core already ships the generated client). Use BoxClient, BoxCcgAuth, CcgConfig, and BoxApiException (or the SDK's API error type) from that package. Also add Microsoft.AspNetCore.App and a test SDK such as xUnit.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

The tutorial's Build by hand samples are Python and TypeScript. Use those as the behavioral spec for CCG enterprise auth, extract_structured with the metadata template (not inline fields), 409 metadata upsert with JSON-Patch op add, and webhook handling. Adapt the HTTP layer to an ASP.NET Core API controller. Call client.Ai.CreateAiExtractStructuredAsync with a metadata template (TemplateKey + Scope enterprise). Keep listen on port 5000 for the local curl test (urls=http://127.0.0.1:5000).

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- a Box client factory/service, ExtractService, MetadataService, and a webhook controller with POST /webhook
- an idiomatic ASP.NET Core layout; keep Box client, extract, and metadata in dedicated services separate from the API controller
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md .NET + Minimal APIs theme={null}
Build a production-minded invoice intake service by following this Box tutorial:
https://developer.box.com/tutorials/invoice-intake

Use .NET 8+ with ASP.NET Core Minimal APIs. Use NuGet and exactly one Box package: Box.V2.Core version 10 or later (do NOT also install Box.Sdk.Gen — v10 of Box.V2.Core already ships the generated client). Use BoxClient, BoxCcgAuth, CcgConfig, and BoxApiException (or the SDK's API error type) from that package. Also add a test SDK such as xUnit.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise metadata template key: <TEMPLATE_KEY>
  (fields vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, currency)
- Invoices Inbox folder ID: <FOLDER_ID>, shared with the app service account as Editor
- Enterprise ID: <ENTERPRISE_ID>
- CCG app scopes enabled: Read and write all files and folders stored in Box,
  Manage AI, and Manage webhooks

The tutorial's Build by hand samples are Python and TypeScript. Use those as the behavioral spec for CCG enterprise auth, extract_structured with the metadata template (not inline fields), 409 metadata upsert with JSON-Patch op add, and webhook handling. Adapt only the HTTP layer to Minimal APIs (MapPost). Call client.Ai.CreateAiExtractStructuredAsync with a metadata template (TemplateKey + Scope enterprise). Keep listen on port 5000 for the local curl test (urls=http://127.0.0.1:5000).

The app must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Receive Box FILE.UPLOADED webhook events at POST /webhook.
3. Ignore events for non-PDF files; return 200 with a clear skipped/ignored status.
4. Call POST /2.0/ai/extract_structured using the invoice metadata template
   (template_key + scope enterprise), not inline fields.
5. Extract vendorName, invoiceNumber, invoiceDate, dueDate, totalAmount, and currency.
   Some fields may be missing when the PDF omits them — that is OK.
6. Write the extracted values back to the file as Box enterprise metadata:
   - Try create first.
   - On 409 Conflict (instance already exists), JSON-Patch update with op 'add'
     for each returned field (not 'replace'). Do not fail retests of the same file.
7. Return clear JSON responses and handle Box API errors safely.
8. Include a local test path that does not require a public webhook URL
   (curl POST to localhost:5000/webhook with a simulated FILE.UPLOADED payload).

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID,
BOX_METADATA_TEMPLATE_KEY, and INVOICES_FOLDER_ID.
INVOICES_FOLDER_ID is for registering the production webhook only —
do not require it inside the POST /webhook handler.

Create a complete runnable project with:
- a Box client factory, ExtractService, MetadataService, and Program.cs with MapPost("/webhook", ...)
- an idiomatic Minimal APIs layout (MapPost in Program.cs); keep Box client, extract, and metadata in dedicated classes separate from endpoint mapping
- dependency and run commands
- .env.example and .gitignore files
- brief webhook signature verification guidance (link or comment is enough;
  do not block the local curl test on signature checks)
- idempotency: the 409 metadata upsert above is required; optionally also
  document skipping a second AI extract when an instance already exists
- focused unit tests and a README with setup and test steps

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

Review generated code before using it in production. Never paste Box credentials into your
coding agent.

When the agent finishes, copy `.env.example` to `.env` and fill in your client ID, client secret, enterprise ID, metadata template key, and folder ID. Then skip ahead to [Run and verify](#run-and-verify).

Prefer to write the code yourself? See [Build by hand](#build-by-hand) below.

## Build by hand

Use this path if you prefer to write the code yourself, or if you need a reference when the agent drifts. Complete [Before you start](#before-you-start) first, then follow the steps in order. Use the language tabs in each code block to switch between Python and TypeScript.

You can also clone a working sample if you prefer to start from running code:

> [card] [Python working sample](https://github.com/box-community/box-automate-invoice-intake)
>
> Clone the Flask app, add your Box credentials, and run.

> [card] [TypeScript working sample](https://github.com/box-community/box-automate-invoice-intake-typescript)
>
> Clone the Express app, add your Box credentials, and run.

> [accordion] 1. Set up the development environment
>
> 1. Open your terminal and create a new project directory:
>
> ```bash theme={null}
> mkdir invoice-intake && cd invoice-intake
> ```
>
> 2. Install dependencies for your language:
>
> ```bash Python theme={null}
> python3 -m venv .venv
> source .venv/bin/activate
> pip install "boxsdk~=10.0" flask python-dotenv
> ```
>
> ```bash TypeScript theme={null}
> npm init -y
> npm install box-node-sdk@10 express dotenv
> npm install -D typescript tsx @types/node @types/express
> npx tsc --init --rootDir . --outDir dist --module commonjs --moduleResolution node --esModuleInterop --strict
> ```
>
> > [!NOTE]
> >
> > **Python:** After activation, your terminal prompt shows `(.venv)` at the beginning. Every time you open a new terminal window or tab, re-activate the virtual environment with `source .venv/bin/activate` from the project directory. If you see `ModuleNotFoundError`, the venv is usually not activated.
> >
> > **TypeScript:** `tsx` runs TypeScript directly during development. You can compile with `npx tsc` for production builds.
>
> 3. Create a `.env` file to store your credentials then add the following content. Replace the placeholder values with your actual credentials from the Box Developer Console:
>
> ```bash theme={null}
> BOX_CLIENT_ID=your_client_id
> BOX_CLIENT_SECRET=your_client_secret
> BOX_ENTERPRISE_ID=your_enterprise_id
> BOX_METADATA_TEMPLATE_KEY=your_metadata_template_key
> INVOICES_FOLDER_ID=your_folder_id
> ```
>
> > [!WARNING]
> >
> > Never commit `.env` files to version control. Add `.env` to your `.gitignore`.
>
> > [!NOTE]
> >
> > **Understanding environment variables:** The `.env` file stores sensitive values (your actual credentials). Your code reads these values by referencing their **names**. When you copy the code in the following steps, keep the quoted variable names exactly as shown. Do not replace them with your actual credentials.

> [accordion] 2. Authenticate the Box client
>
> Create the Box client module in your project directory:
>
> ```python Python theme={null}
> # box_client.py
> import os
> from dotenv import load_dotenv
> from box_sdk_gen import (
>     BoxClient,
>     BoxCCGAuth,
>     CCGConfig,
> )
>
> load_dotenv()
>
> def get_box_client() -> BoxClient:
>     config = CCGConfig(
>         client_id=os.getenv("BOX_CLIENT_ID"),
>         client_secret=os.getenv("BOX_CLIENT_SECRET"),
>         enterprise_id=os.getenv("BOX_ENTERPRISE_ID"),
>     )
>     auth = BoxCCGAuth(config=config)
>     return BoxClient(auth=auth)
> ```
>
> ```typescript TypeScript theme={null}
> // boxClient.ts
> import 'dotenv/config';
> import { BoxClient, BoxCcgAuth, CcgConfig } from 'box-node-sdk';
>
> export function getBoxClient(): BoxClient {
>   const config = new CcgConfig({
>     clientId: process.env.BOX_CLIENT_ID!,
>     clientSecret: process.env.BOX_CLIENT_SECRET!,
>     enterpriseId: process.env.BOX_ENTERPRISE_ID!,
>   });
>   const auth = new BoxCcgAuth({ config });
>   return new BoxClient({ auth });
> }
> ```
>
> > [!TIP]
> >
> > Client Credentials Grant is recommended for server-to-server automations where no end user is present. For other authentication options, see the authentication overview.

> [accordion] 3. Build the extraction function
>
> Create the extraction module. This is the core of the service. It takes a file ID, calls Box AI to extract fields using your metadata template, and returns the structured result.
>
> ```python Python theme={null}
> # extract.py
> import os
> from dotenv import load_dotenv
> from box_sdk_gen import (
>     AiItemBase,
>     BoxClient,
>     CreateAiExtractStructuredMetadataTemplate,
>     CreateAiExtractStructuredMetadataTemplateTypeField,
> )
>
> load_dotenv()
>
> def extract_invoice_fields(client: BoxClient, file_id: str) -> dict:
>     template_key = os.getenv("BOX_METADATA_TEMPLATE_KEY")
>
>     result = client.ai.create_ai_extract_structured(
>         items=[AiItemBase(id=file_id)],
>         metadata_template=CreateAiExtractStructuredMetadataTemplate(
>             template_key=template_key,
>             type=CreateAiExtractStructuredMetadataTemplateTypeField.METADATA_TEMPLATE,
>             scope="enterprise",
>         ),
>     )
>
>     return result.to_dict()["answer"]
> ```
>
> ```typescript TypeScript theme={null}
> // extract.ts
> import 'dotenv/config';
> import { BoxClient } from 'box-node-sdk';
> import { AiItemBase } from 'box-node-sdk/schemas/aiItemBase';
>
> export async function extractInvoiceFields(
>   client: BoxClient,
>   fileId: string,
> ): Promise<Record<string, unknown>> {
>   const templateKey = process.env.BOX_METADATA_TEMPLATE_KEY!;
>
>   const result = await client.ai.createAiExtractStructured({
>     items: [new AiItemBase({ id: fileId })],
>     metadataTemplate: {
>       templateKey,
>       type: 'metadata_template',
>       scope: 'enterprise',
>     },
>   });
>
>   return result.answer as Record<string, unknown>;
> }
> ```
>
> The metadata template tells Box AI exactly which fields to look for and what data types to return. This means the response shape is predictable and consistent, regardless of how each vendor formats their invoices.

> [accordion] 4. Write metadata back to the file
>
> Create the metadata module. After extraction, this function attaches the extracted values to the file as a metadata instance:
>
> ```python Python theme={null}
> # metadata.py
> import os
> from dotenv import load_dotenv
> from box_sdk_gen import (
>     BoxAPIError,
>     BoxClient,
>     CreateFileMetadataByIdScope,
>     UpdateFileMetadataByIdRequestBody,
>     UpdateFileMetadataByIdRequestBodyOpField,
>     UpdateFileMetadataByIdScope,
> )
>
> load_dotenv()
>
> def apply_metadata(client: BoxClient, file_id: str, metadata: dict) -> dict:
>     template_key = os.getenv("BOX_METADATA_TEMPLATE_KEY")
>
>     try:
>         attached = client.file_metadata.create_file_metadata_by_id(
>             file_id=file_id,
>             scope=CreateFileMetadataByIdScope.ENTERPRISE,
>             template_key=template_key,
>             request_body=metadata,
>         )
>     except BoxAPIError as error:
>         if error.response_info.status_code != 409:
>             raise
>
>         attached = client.file_metadata.update_file_metadata_by_id(
>             file_id=file_id,
>             scope=UpdateFileMetadataByIdScope.ENTERPRISE,
>             template_key=template_key,
>             request_body=[
>                 UpdateFileMetadataByIdRequestBody(
>                     op=UpdateFileMetadataByIdRequestBodyOpField.ADD,
>                     path=f"/{key}",
>                     value=value,
>                 )
>                 for key, value in metadata.items()
>             ],
>         )
>
>     return attached.to_dict()
> ```
>
> ```typescript TypeScript theme={null}
> // metadata.ts
> import 'dotenv/config';
> import { BoxApiError, BoxClient } from 'box-node-sdk';
>
> export async function applyMetadata(
>   client: BoxClient,
>   fileId: string,
>   metadata: Record<string, unknown>,
> ) {
>   const templateKey = process.env.BOX_METADATA_TEMPLATE_KEY!;
>
>   try {
>     return await client.fileMetadata.createFileMetadataById(
>       fileId,
>       'enterprise',
>       templateKey,
>       metadata,
>     );
>   } catch (error) {
>     if (!(error instanceof BoxApiError) || error.responseInfo.statusCode !== 409) {
>       throw error;
>     }
>
>     return client.fileMetadata.updateFileMetadataById(
>       fileId,
>       'enterprise',
>       templateKey,
>       Object.entries(metadata).map(([key, value]) => ({
>         op: 'add' as const,
>         path: `/${key}`,
>         value,
>       })),
>     );
>   }
> }
> ```
>
> > [!NOTE]
> >
> > Creating metadata only succeeds the first time. If the file already has an instance of the template, Box returns `409 Conflict on Metadata Instance`, so this function falls back to a JSON-Patch update. That keeps the service safe to re-run on a file you already processed, which happens with duplicate webhook deliveries and resent invoices.
> >
> > Use the `add` operation rather than `replace`. `add` sets a value whether or not the field is already present, so the update still succeeds when Box AI returns fewer fields than the previous run.
>
> Once metadata is attached, the extracted fields become searchable, filterable, and visible in the Box web app. You can use metadata queries to find all invoices above a certain amount, filter by vendor, or build dashboards in Box Apps.

> [accordion] 5. Create the webhook listener
>
> Create the HTTP application that receives webhook notifications when new files arrive in the inbox folder:
>
> ```python Python theme={null}
> # app.py
> import os
> import json
>
> from dotenv import load_dotenv
> from flask import Flask, request, jsonify
>
> from box_client import get_box_client
> from extract import extract_invoice_fields
> from metadata import apply_metadata
>
> load_dotenv()
> app = Flask(__name__)
>
> @app.route("/webhook", methods=["POST"])
> def handle_webhook():
>     payload = request.get_json()
>
>     if payload.get("trigger") != "FILE.UPLOADED":
>         return jsonify({"status": "ignored"}), 200
>
>     file_id = payload["source"]["id"]
>     file_name = payload["source"]["name"]
>
>     if not file_name.lower().endswith(".pdf"):
>         return jsonify({"status": "skipped, not a PDF"}), 200
>
>     client = get_box_client()
>
>     extracted = extract_invoice_fields(client, file_id)
>     print(f"Extracted from {file_name}: {json.dumps(extracted, indent=2)}")
>
>     apply_metadata(client, file_id, extracted)
>     print(f"Metadata applied to file {file_id}")
>
>     return jsonify({"status": "processed", "file_id": file_id}), 200
>
> if __name__ == "__main__":
>     app.run(port=5000)
> ```
>
> ```typescript TypeScript theme={null}
> // app.ts
> import express, { Request, Response } from 'express';
> import { getBoxClient } from './boxClient';
> import { extractInvoiceFields } from './extract';
> import { applyMetadata } from './metadata';
>
> const app = express();
> app.use(express.json());
>
> app.post('/webhook', async (req: Request, res: Response) => {
>   const payload = req.body;
>
>   if (payload?.trigger !== 'FILE.UPLOADED') {
>     res.status(200).json({ status: 'ignored' });
>     return;
>   }
>
>   const fileId = payload.source.id as string;
>   const fileName = payload.source.name as string;
>
>   if (!fileName.toLowerCase().endsWith('.pdf')) {
>     res.status(200).json({ status: 'skipped, not a PDF' });
>     return;
>   }
>
>   const client = getBoxClient();
>
>   const extracted = await extractInvoiceFields(client, fileId);
>   console.log(`Extracted from ${fileName}:`, JSON.stringify(extracted, null, 2));
>
>   await applyMetadata(client, fileId, extracted);
>   console.log(`Metadata applied to file ${fileId}`);
>
>   res.status(200).json({ status: 'processed', file_id: fileId });
> });
>
> app.listen(5000, () => {
>   console.log('Listening on http://127.0.0.1:5000');
> });
> ```
>
> > [!NOTE]
> >
> > In production, you should verify webhook signatures to confirm that requests originate from Box. See Verify webhook signatures for implementation details.
>
> At this point, your project directory should contain the following files:
>
> ```text Python theme={null}
> invoice-intake/
> ├── .env
> ├── .venv/
> ├── app.py
> ├── box_client.py
> ├── extract.py
> └── metadata.py
> ```
>
> ```text TypeScript theme={null}
> invoice-intake/
> ├── .env
> ├── package.json
> ├── tsconfig.json
> ├── node_modules/
> ├── app.ts
> ├── boxClient.ts
> ├── extract.ts
> └── metadata.ts
> ```

When you finish scaffolding, continue to [Run and verify](#run-and-verify).

## Run and verify

You can test the extraction pipeline locally without setting up a public URL or webhook. This simulates what Box would send when a new file arrives.

> [!NOTE]
>
> This requires **two terminal windows** open at the same time. Terminal 1 runs the server (which must stay running). Terminal 2 sends a test request to it.

1. **Terminal 1 - start the server.** Make sure you are in the `invoice-intake` directory, then use the command for your stack:

   ```bash Python theme={null}
   # Flask
   cd ~/invoice-intake
   source .venv/bin/activate
   python3 app.py

   # FastAPI (idiomatic package layout)
   cd ~/invoice-intake
   source .venv/bin/activate
   uvicorn app.main:app --host 127.0.0.1 --port 5000
   ```

   ```bash TypeScript theme={null}
   # Express (flat tutorial layout)
   cd ~/invoice-intake
   npx tsx app.ts

   # Fastify (idiomatic src/ layout)
   cd ~/invoice-intake
   npm start
   ```

   ```bash Node theme={null}
   # Express
   cd ~/invoice-intake
   node app.js

   # NestJS
   cd ~/invoice-intake
   npm start
   ```

   ```bash Java theme={null}
   # Spring Boot
   cd ~/invoice-intake
   export PATH="/opt/homebrew/opt/openjdk@17/bin:$PATH"   # if needed
   mvn spring-boot:run

   # Quarkus
   cd ~/invoice-intake
   export PATH="/opt/homebrew/opt/openjdk@17/bin:$PATH"   # if needed
   mvn quarkus:dev
   ```

   ```bash .NET theme={null}
   # ASP.NET Core or Minimal APIs
   # From the web project directory (or pass --project <path-to-csproj>)
   cd ~/invoice-intake
   dotnet run
   ```

   You should see the server listening on port 5000. Leave this terminal running.

2. **Terminal 2 - send a test request.** Open a new terminal tab or window. Send a simulated webhook payload using curl. Replace `<FILE_ID>` with the **file ID** of the invoice PDF you uploaded to Box.

   > [!WARNING]
   >
   > Use the file ID, not the folder ID. The file ID comes from the file's URL: `https://app.box.com/file/123456789` → the file ID is `123456789`. The folder ID comes from a different URL pattern: `https://app.box.com/folder/987654321`.

   ```bash theme={null}
   curl -X POST http://127.0.0.1:5000/webhook \
     -H "Content-Type: application/json" \
     -d '{
       "trigger": "FILE.UPLOADED",
       "source": {
         "id": "<FILE_ID>",
         "name": "sample-invoice.pdf"
       }
     }'
   ```

3. **Check the result.** Switch back to Terminal 1. You should see the extracted fields printed, followed by a confirmation that metadata was applied:

   ```
   Extracted from sample-invoice.pdf: {
     "vendorName": "ACME Corp",
     "invoiceNumber": "INV-001",
     "invoiceDate": "2025-03-15T00:00:00Z",
     "dueDate": "2025-04-15T00:00:00Z",
     "totalAmount": 1250.00,
     "currency": "USD"
   }
   Metadata applied to file 123456789
   ```

   Open the file in Box and select the **Metadata** tab to verify the values were written correctly.

## Register a webhook for production

The local curl test simulates what Box sends, but for a production deployment you need Box to send real webhook notifications automatically. This requires a publicly accessible HTTPS endpoint:

```bash theme={null}
curl -X POST https://api.box.com/2.0/webhooks \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "target": {
      "id": "<FOLDER_ID>",
      "type": "folder"
    },
    "address": "<webhook_url>",
    "triggers": ["FILE.UPLOADED"]
  }'
```

Replace `<FOLDER_ID>` with your invoices folder ID and update the `address` to your tunnel URL with `/webhook` appended.

Once registered, any PDF uploaded to the folder automatically triggers extraction and metadata application.

## Optional: push totals to an ERP

Once you have structured metadata, pushing data downstream is straightforward. After metadata is applied, start from the Box AI extract object:

```json theme={null}
{
  "vendorName": "ACME Corp",
  "invoiceNumber": "INV-001",
  "invoiceDate": "2025-03-15T00:00:00Z",
  "dueDate": "2025-04-15T00:00:00Z",
  "totalAmount": 1250.00,
  "currency": "USD"
}
```

Map those fields (and the Box file ID, if your ERP needs an external reference) into whatever shape your ERP expects, then POST with your stack's normal HTTP client.

## Scaling to production

> [accordion] Handle duplicate deliveries
>
> Box webhook delivery can produce duplicates. The 409 fallback in `apply_metadata` already keeps the write safe, but a duplicate still pays for a second Box AI extraction. To skip that work, check for an existing instance with `GET /2.0/files/:id/metadata/enterprise/:template` at the top of the handler and return early if one is present.
>
> Only skip when a repeat run is redundant. If vendors resend corrected invoices under the same file ID, let the extraction run so the metadata reflects the latest version.

> [accordion] Process at scale with event streams
>
> For high-volume environments, consider using enterprise events instead of webhooks. Enterprise events provide a durable, polling-based stream that is better suited to batch processing thousands of invoices.

> [accordion] Use the Enhanced Extract Agent for complex invoices
>
> If your invoices contain complex layouts, multi-page line items, or non-standard formatting, use the Enhanced Extract Agent for improved accuracy. Add this agent reference to your existing `POST /2.0/ai/extract_structured` call (alongside the metadata template):
>
> ```json theme={null}
> {
>   "ai_agent": {
>     "type": "ai_agent_id",
>     "id": "enhanced_extract_agent"
>   }
> }
> ```
>
> Pass it the same way your SDK already passes `metadata_template` / `metadataTemplate`. For SDK-specific samples, see the Enhanced Extract Agent quick start.

## Troubleshooting

> [accordion] ModuleNotFoundError: No module named '...'
>
> Your Python virtual environment is not activated. Run `source .venv/bin/activate` from the project directory before running any `python3` commands. Each new terminal tab needs its own activation.

> [accordion] Cannot find module 'box-node-sdk' or similar
>
> From the project directory, run `npm install`. Confirm `box-node-sdk` appears in `package.json` dependencies and that you are using Node.js 20 or higher (`node -v`).

> [accordion] invalid\_client: The client credentials are invalid
>
> Check your `.env` file:
>
> * Verify `BOX_CLIENT_ID` and `BOX_CLIENT_SECRET` match the values in Developer Console > Configuration.
> * Confirm `BOX_ENTERPRISE_ID` is your enterprise ID (found in Admin Console > Account & Billing, or Developer Console > icon in the top-right > Copy Enterprise ID).
> * Ensure your app is authorized in the Developer Console.
> * Make sure the app type is Client Credentials Grant.

> [accordion] 404 Not Found
>
> The service account does not have access to the file or folder. Invite the service account email (found in Developer Console > your app > **Configuration** > **App Details** sidebar) as a collaborator with **Editor** role on the folder containing your invoice files.

> [accordion] metadata\_template must have both scope and template\_key
>
> The `BOX_METADATA_TEMPLATE_KEY` value in your `.env` file is missing or empty. Add the template key you noted when creating the metadata template in [Before you start](#before-you-start).

> [accordion] 409 Conflict on Metadata Instance
>
> The file already has an instance of the template, so creating one fails. This is common when you retest a file that a previous run already processed. Extraction succeeded; only the metadata write failed.
>
> Add the 409 fallback shown in [Build by hand](#build-by-hand) under **4. Write metadata back to the file** so the service updates the existing instance instead of creating a second one. To retest with a clean file, remove the instance from the file's **Metadata** tab in Box, or delete it through the API:
>
> ```bash theme={null}
> curl -X DELETE "https://api.box.com/2.0/files/<FILE_ID>/metadata/enterprise/<TEMPLATE_KEY>" \
>   -H "Authorization: Bearer <ACCESS_TOKEN>"
> ```

> [accordion] The agent tried to create the template or folder
>
> The template, inbox folder, and enterprise ID come from [Before you start](#before-you-start); an agent cannot create them. Re-paste the prompt with the prerequisites block intact so the agent reads `BOX_METADATA_TEMPLATE_KEY`, `INVOICES_FOLDER_ID`, and `BOX_ENTERPRISE_ID` from the environment, or follow [Build by hand](#build-by-hand).

## Next steps

> [card] Sales RFP answer bank
>
> Build an AI-powered knowledge base for sales teams using Box Hubs and Box AI.

> [card] Extract API reference
>
> See the full API specification for structured extraction.

**RELATED GUIDES**
