APIs in Business Central
Business Central exposes REST endpoints (versioned, OData‑style) for core entities such as customers, sales orders, and journals. Developers can also publish custom API pages that surface bespoke tables and logic, letting partner systems push or pull data exactly where it belongs. Typical scenarios include e‑commerce order ingestion, supplier price updates, Power Platform automation, and integrating BC with external BI stacks. Internally, AL code can reach out to other web services—anything that speaks HTTP/JSON. The heavy‑lifting is done by the HttpClient data type, a thin wrapper around .NET System.Net.Http.HttpClient and, from BC 2023 wave 2 onward, by the higher‑level Rest Client codeunit.Why does this matter? Because nearly every BC implementation now requires near‑real‑time data exchange, and the built‑in tooling gives you first‑class, server‑side HTTP access without leaving AL .
Authentication and Connection Fundamentals
Environment endpoints
Every SaaS environment has a URL pattern like https://api.businesscentral.dynamics.com/v2.0/{tenantId}/{environmentName}/api/v2.0 – note the tenant and environment segments; requests pointed at Sandbox will never reach Production (a surprisingly common mis‑routing bug).OAuth 2.0 flows
Microsoft requires OAuth 2.0 for all production BC APIs; Web Service Access Keys (basic auth) are retired for SaaS. The Client‑Credentials (service‑to‑service) flow is ideal for unattended integrations, while the Authorization‑Code flow is used when calls need to run in a user context (e.g., a Power App reading BC on behalf of the signed‑in user).// Acquire token with Client‑Credentials
var
OAuth2: Codeunit "OAuth2";
Token : SecretText;
Scope : Text := 'https://api.businesscentral.dynamics.com/.default';
begin
if OAuth2.AcquireTokenWithClientCredentials(
ClientId, ClientSecret,
'https://login.microsoftonline.com/' + TenantId,
'', Scope, Token)
then
HttpClient.DefaultRequestHeaders().
Add('Authorization', 'Bearer ' + Token);
end;
The OAuth2 helper returns a SecretText so the access token never leaks to the debugger. When testing, Postman’s built‑in OAuth tab lets you obtain the same token interactively.
Registering the app
- Create an App Registration in Microsoft Entra ID (Azure AD).
- Add the Financials.ReadWrite.All (or finer‑grained) permission.
- Copy the Application (client) ID and secret/certificate.
- In BC, open Azure Active Directory Applications, click New, paste the Client ID, and grant consent.
Efficient and Secure Consumption – Best Practices
Topic | Why it matters | How to implement |
Rate limits | BC enforces per‑environment caps (number of concurrent connections, request size, 10‑minute execution time‑out) | Build retry logic that respects Retry‑After headers and back‑off exponentially on HTTP 429 responses. |
Connection reuse | Opening sockets per call exhausts ports | Declare a single‑instance codeunit holding HttpClient or use a shared Rest Client; BC’s runtime already leverages HttpClientFactory behind the scenes, but avoid creating new clients in tight loops. |
Batching | Bundling multiple CRUD ops into one $batch saves round‑trips and stays under throttling limits | POST a multipart $batch payload; make it transactional by adding the Prefer: odata.continue-on-error header only when you do want partial success. |
Timeouts & pagination | Long queries get 504s; large result sets load slowly | Filter queries ($top, $skipToken) and process pages incrementally. Keep request body small—32 MB is the upper bound. |
Security hygiene | Secrets in source control are a breach waiting to happen | Store client secrets in Key Vault or BC Isolated Storage; rely on SecretText in AL so values never leave memory. |
Choosing Between HttpClient and Rest Client
- HttpClient gives full control (custom verbs, fine‑grained header management) but is verbose; you must read the stream, check status codes, and parse JSON manually.
- Rest Client wraps common patterns into one‑liners, auto‑throws on non‑2xx status codes, and can convert the body directly to JsonObject, Blob, or Text.
- Rest Client adds helpers such as SetAuthorizationHeader() and a default user‑agent string (Dynamics 365 Business Central – <Publisher>/<AppVersion>).
// Rest Client one‑liner
var CustomerJObj: JsonObject;
begin
CustomerJObj :=
RestClient.GetAsJson(ApiBaseUrl + '/customers?$top=1')
.AsObject(); // Throws on 4xx/5xx
end;
Common Challenges (and Fixes)
- 401 Unauthorized – Check that the token’s scope matches the endpoint and that the AAD app is enabled in the target environment.
- 429 Too Many Requests – Implement exponential back‑off and leverage OData $batch or $top pagination to reduce call volume .
- Invalid JSON date formats – Remember BC expects ISO 8601 (yyyy‑MM‑dd) when you POST; map and pre‑format in your integration layer.
- $metadata mismatch after upgrade – Regenerate client proxies or strongly typed DTOs after each major BC wave to avoid field renaming issues.
- Socket exhaustion in test harnesses – Dispose test HttpClient instances or run them through a single static client.
Debugging, Monitoring, and Maintenance
- Telemetry – Every incoming and outgoing web‑service call is logged to partner telemetry; hook Application Insights or Log Analytics queries to track slow calls, 4xx/5xx rates, and top endpoints.
- Try‑functions & Error dialogs – Wrap risky calls in procedure MyTry(var IsHandled: Boolean) or try .. catch and surface actionable, localised messages.
- Fiddler/Postman – When calls fail, reproduce them outside BC. Postman’s code tab will even generate a C# or JavaScript snippet you can paste into unit tests.
- Feature updates – New AL compiler warnings flag obsolete API versions; schedule technical upgrade tasks each wave to adjust endpoint versions.
- Job Queue – Schedule integration codeunits during off‑peak hours to reduce contention and stay within tenant limits.
Conclusion
Business Central gives AL developers two robust ways to call external services—HttpClient for total control and Rest Client for rapid coding. Couple these with secure OAuth 2.0 patterns, respect the platform’s throttling limits, and instrument your integrations with telemetry. Follow the practices above and your connectors will be secure, fast, and upgrade‑proof, ensuring BC remains at the heart of a healthy, API‑driven ecosystem.Sources
- Call web services with AL Rest Client module
- Using service-to-service (S2S) authentication
- Configuring Business Central for Azure Active Directory authentication and OAuth (2)
- How to get Access Token in Business Central using OAuth2 Codeunit
- How To Use Postman To Connect With Business Central APIs
- Registering Dynamics 365 Business Central Application in Azure
- Current API Limits
- Using OData transactional $batch requests
- Call web services with AL Rest Client module
- Codeunit "Rest Client"
- How to Authenticate Through Azure Active Directory (AAD) to Use Microsoft Dynamics 365 Business Central API
- The Building Blocks of AL’s HTTP Integration in Dynamics 365 BC
- Web Service Telemetry
- AL error handling
- Business Central Online API Successful token but wrong credentials