# Connecting an AI Agent to Business Central: API v2.0 and Web Services

> The agent obtains a token from Microsoft Entra ID via the client credentials flow and calls the standard API v2.0 at /companies({id})/customers, /items or /salesOrders. The app must be registered inside Business Central and given narrowly scoped permission sets.

Canonical URL: https://www.ruebstudio.de/en/guides/ai-agent-integrations/ai-agent-business-central-api  
Author: Dr.-Ing. Marcus Rüb, CEO  
Published: 2026-11-26

Many mid-sized companies run Microsoft Dynamics 365 Business Central as their ERP, and that is where orders, items and customer accounts live. An AI agent that drafts quotes or answers delivery questions needs exactly that data. This tutorial uses the standard API v2.0 with service-to-service authentication (as of November 2026) and explains when custom API pages or published web services are the better fit.

For the wider Dynamics 365 family, including Sales and Customer Service on Dataverse, see [Connecting an AI Agent to Microsoft Dynamics 365](https://www.ruebstudio.de/en/guides/ai-agent-integrations/connect-ai-agent-dynamics-365). Business Central works differently: its own API host, its own permission model, and a company ID in every data URL.

## What you will build

You will end up with a small Python module that signs in to Business Central online without a user, reads customers, items and sales orders, and can create sales orders as drafts. Those functions become the agent's tools. Posting stays with a person.

A typical flow: a customer emails asking for a price and delivery date. The agent looks up the item and its inventory, checks whether the customer account is blocked or carries a large outstanding balance, and prepares a draft order for the sales office to review. The [quotation agent page](https://www.ruebstudio.de/en/ai-agents/quotation) shows how this fits into a quoting process.

## Prerequisites

You need Business Central online, admin rights in Microsoft Entra ID and in Business Central, and Python 3.10 or later with the `requests` library. Start in a sandbox environment, never in production.

- **API v2.0:** according to [Microsoft](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/), the APIs are enabled by default in Business Central online. API v1.0 was removed in version 28.0 (2026 release wave 1), as listed in the [deprecated features](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/upgrade/deprecated-features-w1).
- **Environment name**, for example `sandbox` or `production`, from the admin centre.
- **Tenant details:** the tenant ID for the token endpoint and the domain name used in the API URL.
- **Credentials** in environment variables only.

## Step 1: Register an app in Microsoft Entra ID

The agent signs in as an application, not as a person. Microsoft's [service-to-service guide](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/automation-apis-using-s2s-authentication) uses the OAuth 2.0 client credentials flow for this. You need an app registration with a client ID and a secret.

1. Register a new app in the Microsoft Entra admin centre and note the Application (client) ID.
2. Under Certificates & secrets, create a client secret. Its value is shown once only.
3. Under API permissions, pick Dynamics 365 Business Central and add the **application** permission `API.ReadWrite.All`. `Automation.ReadWrite.All` is only for the automation APIs under `/api/microsoft/automation`, which handle administration rather than business data.

For production, a certificate is sturdier than a secret: secrets expire and leak more easily.

## Step 2: Enable the app in Business Central and assign permission sets

The Entra permission alone grants no data access. Inside Business Central you add the app on the Microsoft Entra Applications page, set its state to Enabled and assign permission sets. Those sets decide what the agent can see and change.

- Enter the client ID and a description, set the state to Enabled.
- Assign permission sets per company. Microsoft states that applications cannot be given the **SUPER** set.
- A read-only agent gets read access to customers, items and sales documents, nothing more. Add write access only once it should create drafts.

This is where security is really decided. `API.ReadWrite.All` sounds broad, but effective rights come from the permission sets.

## Step 3: Get a token and the company ID

Tokens come from `https://login.microsoftonline.com/<tenantId>/oauth2/v2.0/token` with the scope `https://api.businesscentral.dynamics.com/.default`. Then list the companies, because every business-data URL carries the company ID as a GUID.

Per the [endpoint documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/endpoints-apis-for-dynamics), the base URL is `https://api.businesscentral.dynamics.com/v2.0/<domain>/<environment>/api/v2.0`.

```python
import os
import requests

TENANT_ID = os.environ["BC_TENANT_ID"]          # used for the token endpoint
TENANT_DOMAIN = os.environ["BC_TENANT_DOMAIN"]  # e.g. contoso.com
ENVIRONMENT = os.environ.get("BC_ENVIRONMENT", "sandbox")
BASE = f"https://api.businesscentral.dynamics.com/v2.0/{TENANT_DOMAIN}/{ENVIRONMENT}/api/v2.0"


def get_token() -> str:
    resp = requests.post(
        f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token",
        data={
            "grant_type": "client_credentials",
            "client_id": os.environ["BC_CLIENT_ID"],
            "client_secret": os.environ["BC_CLIENT_SECRET"],
            "scope": "https://api.businesscentral.dynamics.com/.default",
        },
        timeout=30,
    )
    resp.raise_for_status()
    return resp.json()["access_token"]


def bc_get(url: str, token: str, params: dict | None = None) -> dict:
    resp = requests.get(url, headers={"Authorization": f"Bearer {token}"},
                        params=params, timeout=60)
    resp.raise_for_status()
    return resp.json()


token = get_token()
for c in bc_get(f"{BASE}/companies", token)["value"]:
    print(c["id"], c["name"])  # id is the company ID for all later calls
```

Fix the company ID in the agent's configuration. An agent that picks its own company will eventually write into the wrong one.

## Step 4: Read customers, items and sales orders

All business data sits below `/companies({id})/`. Most agents need three entities: `customers`, `items` and `salesOrders` with their `salesOrderLines`. Request only the fields the agent needs and filter on the server.

Microsoft's [OData performance notes](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/webservices/odata-client-performance) advise narrowing columns with `$select` and not using `$top` and `$skip` for client-side paging; use server-driven paging instead. The next page arrives as a next link, named `@odata.nextLink` or `@nextLink` depending on the protocol version, per the [OData JSON format specification](https://docs.oasis-open.org/odata/odata-json-format/v4.01/odata-json-format-v4.01.html).

```python
def bc_list(company_id: str, entity: str, token: str, params: dict) -> list[dict]:
    url = f"{BASE}/companies({company_id})/{entity}"
    rows: list[dict] = []
    while url:
        data = bc_get(url, token, params)
        rows.extend(data["value"])
        url = data.get("@odata.nextLink") or data.get("@nextLink")
        params = None  # the next link is complete; never append options
    return rows


COMPANY = os.environ["BC_COMPANY_ID"]

items = bc_list(COMPANY, "items", token, {
    "$select": "number,displayName,inventory,unitPrice,blocked",
    "$filter": "startswith(displayName,'Pump')",
})

customer = bc_list(COMPANY, "customers", token, {
    "$select": "number,displayName,balanceDue,blocked",
    "$filter": "number eq '10000'",
})

orders = bc_list(COMPANY, "salesOrders", token, {
    "$select": "number,customerNumber,orderDate,status,totalAmountIncludingTax",
    "$filter": "customerNumber eq '10000'",
    "$expand": "salesOrderLines",
})
```

Field names follow Microsoft's resource pages for [salesOrder](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/resources/dynamics_salesorder), item and customer. A customer's `blocked` value can be blank, "Ship", "Invoice" or "All". The agent should always check it before suggesting an order.

## Step 5: Create sales orders as drafts

A new sales order is a POST to `/companies({id})/salesOrders`. Microsoft's [create example](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/api/dynamics_salesorder_create) sends `customerNumber` and `orderDate`, and the service answers `201 Created`.

```python
def create_sales_order(company_id: str, token: str,
                       customer_number: str, order_date: str) -> dict:
    resp = requests.post(
        f"{BASE}/companies({company_id})/salesOrders",
        headers={"Authorization": f"Bearer {token}",
                 "Content-Type": "application/json"},
        json={"customerNumber": customer_number, "orderDate": order_date},
        timeout=60,
    )
    resp.raise_for_status()
    return resp.json()  # includes id, number and status
```

Lines go to `salesOrders({id})/salesOrderLines`. Two rules belong in every implementation:

- **Updates with an ETag:** for PATCH on a sales order, Microsoft lists the `If-Match` header as required. Pass the ETag from your last read. `If-Match: *` skips the check, so an agent using it would silently overwrite a colleague's edits.
- **No posting actions:** the resource offers the bound action `Microsoft.NAV.shipAndInvoice`, which ships and invoices in one go. Do not hand that to the agent. Orders stay in "Draft" or "Open" until a person releases them.

## Step 6: Wrap the reads as agent tools

The agent never calls the API freely. It gets narrow tools with fixed parameters, each wrapping one query from step 4 with a fixed `$select` and a capped result size. That keeps it clear which ERP data reaches the language model.

```python
TOOLS = [
    {
        "name": "search_items",
        "description": "Find items by name prefix. Returns number, name, inventory, price.",
        "input_schema": {
            "type": "object",
            "properties": {"name_prefix": {"type": "string", "maxLength": 40}},
            "required": ["name_prefix"],
        },
    },
    {
        "name": "check_customer",
        "description": "Return name, balance due and blocked status for a customer number.",
        "input_schema": {
            "type": "object",
            "properties": {"customer_number": {"type": "string", "maxLength": 20}},
            "required": ["customer_number"],
        },
    },
]


def search_items(name_prefix: str) -> list[dict]:
    value = name_prefix.replace("'", "''")  # escape OData string literal
    return bc_list(COMPANY, "items", get_token(), {
        "$select": "number,displayName,inventory,unitPrice",
        "$filter": f"startswith(displayName,'{value}')",
    })[:20]
```

The schema works with any model provider that supports tool use. Do not skip the quote escaping: without it, crafted input could rewrite the filter.

## Standard API, custom API pages or published web services?

Start with the standard API v2.0; it covers the common entities. If fields are missing, for example from an industry extension, build custom API pages or API queries. Publishing UI pages as web services is no longer the recommended route for new integrations.

| Route | Use it for | Note |
|---|---|---|
| API v2.0 | customers, items, sales documents | fields cannot be extended, per Microsoft |
| Custom API page | own fields and tables, read and write | `PageType = API`, `ODataKeyFields = SystemId` |
| Custom API query | read-only joins across tables | view only |
| Published page (ODataV4) | legacy integrations | Microsoft pages no longer exposable as OData from version 30 |

A custom API page is served at `/api/<publisher>/<group>/<version>/companies({id})/<entitySetName>`, see [developing a custom API](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-develop-custom-api). The [web service documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/webservices/publish-web-service) tells you to use API pages and API queries for new integrations, and the [platform deprecation list](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/upgrade/deprecated-features-platform) removes exposing Microsoft pages as SOAP endpoints in version 29.0 and as OData endpoints in version 30.0.

Microsoft also runs a [Business Central MCP server](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/ai/mcp-overview) at `https://mcp.businesscentral.dynamics.com`. It uses user sign-in (authorization code with PKCE) and the signed-in user's permissions, and admins choose which API pages and queries it exposes. It suits staff working in a chat client; for how MCP works in general, see [MCP servers for AI agents](https://www.ruebstudio.de/en/guides/ai-agent-integrations/mcp-servers-connect-ai-agents). For an unattended background agent, the service-to-service route above remains the fit. The same page notes that Microsoft plans to introduce charges for MCP tools.

## Testing

Test in the sandbox in three passes: token and company list, then each read function against known records, then the agent with real but anonymised requests. Spend most of the time on failure cases.

- Blocked customer: does the agent spot `blocked = All` and decline to draft an order?
- Item name containing an apostrophe: does the filter survive?
- Missing permissions: the call must fail loudly, not return empty data the agent reads as "no match".
- Large result sets: does paging work, and does the tool trim to the agreed size?

## Operations, limits and security

Business Central online limits OData traffic per user, and Microsoft states that this applies equally to applications. An agent firing many parallel calls will hit those limits. Add retries with back-off and keep concurrency low.

According to Microsoft's [operational limits page](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/operational-limits-online):

- at most 5 concurrent requests per user, with further requests queued;
- 6,000 requests within a sliding five-minute window, after which the service returns HTTP 429;
- a maximum of 20,000 entities per page and 100 operations per `$batch`.

For HTTP 429, the [rate limits page](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/dynamics-rate-limits) calls for retry logic with a cool-off period, such as exponential back-off. Also:

- **One app per agent**, so the change log shows which agent created what, and each can be switched off on its own.
- **Rotate secrets** and monitor expiry, or use a certificate.
- **Log every tool call** with its parameters.
- **Data protection:** customer data reaches the language model. Settle the model provider, data location and processing agreement before going live; with self-hosted models the setup can be operated in line with the GDPR. This tutorial is not legal advice.

When this is the wrong approach: if the data you need sits in extensions without an API and nobody can build custom API pages, the integration turns into a workaround project. Solve the data access question first.

## Next steps

Start with a read-only agent that assembles inventory and customer status for an incoming request. Only once the sales team trusts those suggestions should it start creating draft orders. Posting stays with people.

The overview of [AI agents for businesses](https://www.ruebstudio.de/en/ai-agents) and the [sales agent page](https://www.ruebstudio.de/en/ai-agents/sales) show where such agents fit. If you also run Dynamics 365 Sales or Customer Service, the [Dynamics 365 overview](https://www.ruebstudio.de/en/guides/ai-agent-integrations/connect-ai-agent-dynamics-365) covers the Dataverse route that applies there instead of the Business Central API. If you run SAP Business One rather than Business Central, the main difference is the interface (Service Layer instead of the OData API v2.0), covered in [connecting an AI agent to SAP Business One](https://www.ruebstudio.de/en/guides/ai-agent-integrations/connect-ai-agent-sap-business-one).

## Frequently asked questions

### Which Entra permission does the agent need?

The application permission API.ReadWrite.All on the Dynamics 365 Business Central API. What the agent can actually read or change is decided by the permission sets you assign inside Business Central.

### Should I expose the Customer Card as an OData web service instead?

Not for new work. Microsoft recommends API pages and API queries for new integrations, and from version 30 (2027 release wave 1) Microsoft pages can no longer be exposed as OData endpoints.

### Do service principals get higher rate limits?

No. Microsoft's FAQ states that the per-user limits apply to application users in the same way.

### Is the Business Central MCP server a replacement for this approach?

It suits people working in a chat client under their own identity. A background agent without a signed-in user still needs the service-to-service route described here.

## Sources

- [Microsoft Learn: API (v2.0) for Dynamics 365 Business Central](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/)
- [Microsoft Learn: Endpoints for the APIs for Dynamics 365 Business Central](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/endpoints-apis-for-dynamics)
- [Microsoft Learn: Using Service to Service Authentication](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/automation-apis-using-s2s-authentication)
- [Microsoft Learn: salesOrder resource type (API v2.0)](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/resources/dynamics_salesorder)
- [Microsoft Learn: Create salesOrders](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/api/dynamics_salesorder_create)
- [Microsoft Learn: Operational limits for Business Central online](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/operational-limits-online)
- [Microsoft Learn: Working with API rate limits in Business Central](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/dynamics-rate-limits)
- [Microsoft Learn: Publish a web service](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/webservices/publish-web-service)
- [Microsoft Learn: Deprecated features in the platform](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/upgrade/deprecated-features-platform)
- [Microsoft Learn: Deprecated features in the W1 version](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/upgrade/deprecated-features-w1)
- [Microsoft Learn: Developing a custom API](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-develop-custom-api)
- [Microsoft Learn: OData client performance](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/webservices/odata-client-performance)
- [Microsoft Learn: Business Central MCP Server Overview and Setup](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/ai/mcp-overview)
- [OASIS: OData JSON Format Version 4.01](https://docs.oasis-open.org/odata/odata-json-format/v4.01/odata-json-format-v4.01.html)
