Ava API Client

Guide

AL HttpClient example: call a REST API from Business Central

Updated 21 November 2026

Calling a web service from AL takes four types: HttpClient sends, HttpRequestMessage describes the call, HttpResponseMessage holds the answer, and HttpContent carries a body in either direction. This guide builds a working codeunit from them, one call at a time, and points out the two places where almost every first attempt goes wrong.

A GET request

The smallest useful call: fetch JSON from an address and hand the text back to the caller.

codeunit 50100 "Exchange Rate Client"
{
    procedure GetRates(BaseCurrency: Code[10]; var ResponseText: Text): Boolean
    var
        Client: HttpClient;
        RequestMessage: HttpRequestMessage;
        ResponseMessage: HttpResponseMessage;
        RequestHeaders: HttpHeaders;
        Url: Text;
    begin
        Url := StrSubstNo('https://api.example.com/v1/rates?base=%1', BaseCurrency);

        RequestMessage.Method := 'GET';
        RequestMessage.SetRequestUri(Url);
        RequestMessage.GetHeaders(RequestHeaders);
        RequestHeaders.Add('Accept', 'application/json');

        if not Client.Send(RequestMessage, ResponseMessage) then
            Error('The request to %1 could not be sent. Check the address and your network.', Url);

        ResponseMessage.Content.ReadAs(ResponseText);

        if not ResponseMessage.IsSuccessStatusCode() then
            Error('The service answered %1 %2.\%3',
                ResponseMessage.HttpStatusCode(), ResponseMessage.ReasonPhrase(), ResponseText);

        exit(true);
    end;
}

Three things to notice.

A POST with a JSON body

Sending data adds HttpContent, and with it the pitfall that catches most people: Content-Type belongs to the content's headers, not the request's. Add it to the request headers and the runtime refuses it with a "misused header name" error. It also has to replace the default, because WriteFrom sets text/plain on its own.

    procedure CreateOrder(Order: JsonObject; var ResponseText: Text): Boolean
    var
        Client: HttpClient;
        RequestMessage: HttpRequestMessage;
        ResponseMessage: HttpResponseMessage;
        Content: HttpContent;
        ContentHeaders: HttpHeaders;
        BodyText: Text;
    begin
        Order.WriteTo(BodyText);
        Content.WriteFrom(BodyText);

        // Content-Type goes on the content, and the default must be removed first.
        Content.GetHeaders(ContentHeaders);
        ContentHeaders.Remove('Content-Type');
        ContentHeaders.Add('Content-Type', 'application/json');

        RequestMessage.Method := 'POST';
        RequestMessage.SetRequestUri('https://api.example.com/v1/orders');
        RequestMessage.Content := Content;

        if not Client.Send(RequestMessage, ResponseMessage) then
            Error('The order could not be sent.');

        ResponseMessage.Content.ReadAs(ResponseText);
        if not ResponseMessage.IsSuccessStatusCode() then
            Error('The service refused the order with %1: %2', ResponseMessage.HttpStatusCode(), ResponseText);

        exit(true);
    end;

The same pattern serves PATCH and PUT; only Method changes. For a DELETE there is usually no content at all.

Which headers go where:

HeaderWhere to add it
Authorization, Accept, If-Match, Prefer, anything customRequest headers: RequestMessage.GetHeaders(…), or Client.DefaultRequestHeaders() for every call the client makes.
Content-Type, Content-Length, Content-EncodingContent headers: Content.GetHeaders(…).

Sending a bearer token

Most APIs you call from Business Central want Authorization: Bearer <token>. Keep the token in a SecretText, so it never appears in the debugger or a log, and let the headers take it as one:

    local procedure Authorize(var Client: HttpClient; AccessToken: SecretText)
    begin
        Client.DefaultRequestHeaders().Add('Authorization', SecretStrSubstNo('Bearer %1', AccessToken));
    end;

SecretStrSubstNo is StrSubstNo for secrets: the result is a SecretText too, so the "Bearer " prefix does not force the token into a plain string. Setting it on DefaultRequestHeaders means every request this client sends carries it.

Getting the token: client credentials

For Business Central's own API, or any service behind Microsoft Entra, the token comes from a POST to the token endpoint with the app's client ID and secret. The body is form-encoded, not JSON, and it contains the secret, so it is built as a SecretText as well.

    local procedure AcquireAccessToken(TenantId: Text; ClientId: Text; ClientSecret: SecretText; var AccessToken: SecretText): Boolean
    var
        Client: HttpClient;
        RequestMessage: HttpRequestMessage;
        ResponseMessage: HttpResponseMessage;
        Content: HttpContent;
        ContentHeaders: HttpHeaders;
        Body: SecretText;
        ResponseText: Text;
        JObject: JsonObject;
        JToken: JsonToken;
    begin
        Body := SecretStrSubstNo(
            'grant_type=client_credentials&client_id=%1&client_secret=%2&scope=https://api.businesscentral.dynamics.com/.default',
            ClientId, ClientSecret);
        Content.WriteFrom(Body);
        Content.GetHeaders(ContentHeaders);
        ContentHeaders.Remove('Content-Type');
        ContentHeaders.Add('Content-Type', 'application/x-www-form-urlencoded');

        RequestMessage.Method := 'POST';
        RequestMessage.SetRequestUri(StrSubstNo('https://login.microsoftonline.com/%1/oauth2/v2.0/token', TenantId));
        RequestMessage.Content := Content;

        if not Client.Send(RequestMessage, ResponseMessage) then
            exit(false);
        if not ResponseMessage.IsSuccessStatusCode() then
            exit(false);

        ResponseMessage.Content.ReadAs(ResponseText);
        JObject.ReadFrom(ResponseText);
        if not JObject.Get('access_token', JToken) then
            exit(false);

        AccessToken := JToken.AsValue().AsText();
        exit(true);
    end;

The scope for Business Central is always https://api.businesscentral.dynamics.com/.default. For another Entra-protected API, use its application ID URI followed by /.default. The token lasts about an hour; cache it in a single-instance codeunit and ask for a new one when a call comes back 401, rather than fetching one per request.

Business Central also ships an OAuth2 codeunit in the System Application with procedures such as AcquireTokenWithClientCredentials. It does the same work, handles the token cache, and is the better choice inside an extension you will maintain. The hand-written version above shows what it is doing, and is what you need when the token endpoint is not Entra.

The setup on the Entra and Business Central side, including the permission that is most often missed, is in Connect to the Business Central API with OAuth 2.0.

Reading the JSON reply

The answer arrives as text. JsonObject.ReadFrom parses it, Get fetches a property into a JsonToken, and the token's AsValue, AsObject or AsArray gives you the typed value. A Business Central list comes back under value:

    procedure CustomerNames(ResponseText: Text) Names: List of [Text]
    var
        JObject: JsonObject;
        JToken: JsonToken;
        Item: JsonToken;
        NameToken: JsonToken;
    begin
        if not JObject.ReadFrom(ResponseText) then
            Error('The reply was not JSON: %1', ResponseText);
        if not JObject.Get('value', JToken) then
            exit;

        foreach Item in JToken.AsArray() do
            if Item.AsObject().Get('displayName', NameToken) then
                Names.Add(NameToken.AsValue().AsText());
    end;

Two habits save a lot of debugging. Test the result of Get instead of assuming the property is there; a missing property throws, and the message does not say which one. And read numbers with the matching method, AsDecimal, AsInteger, AsBoolean, rather than taking text and converting it. A null in the JSON is a value token too, and AsValue().IsNull() tells you so before you try to read it.

Errors, timeouts and retries

Decide what each failure should do before you write the Error calls. A background job that stops on the first 503 is not useful; a user action that silently swallows one is worse.

Before it will run

Outbound HTTP from an extension is allowed in production environments of Business Central Online. In a sandbox, calls from an extension are blocked until someone switches on Allow HttpClient Requests for that extension on the Extension Management page. The symptom is a Send that fails straight away, with no response, when the same address works from a browser. Check that setting before you look anywhere else.

On-premises installations can also restrict outbound addresses in the server configuration, and a company proxy may block them again. If a call that works from your laptop fails from the service tier, ask whoever runs the server.

Putting it together

A typical codeunit keeps the client, token and base address together, and exposes small procedures the rest of the extension can call:

codeunit 50101 "Business Central API Client"
{
    SingleInstance = true;

    var
        AccessToken: SecretText;
        TokenAcquired: Boolean;

    procedure ListCustomers(TenantId: Text; Environment: Text; CompanyId: Guid; var ResponseText: Text): Boolean
    var
        Client: HttpClient;
        RequestMessage: HttpRequestMessage;
        ResponseMessage: HttpResponseMessage;
        Url: Text;
    begin
        if not TokenAcquired then
            Error('Call Connect first.');

        Url := StrSubstNo(
            'https://api.businesscentral.dynamics.com/v2.0/%1/%2/api/v2.0/companies(%3)/customers?$select=number,displayName',
            TenantId, Environment, Format(CompanyId, 0, 4));

        Client.DefaultRequestHeaders().Add('Authorization', SecretStrSubstNo('Bearer %1', AccessToken));
        RequestMessage.Method := 'GET';
        RequestMessage.SetRequestUri(Url);

        if not Client.Send(RequestMessage, ResponseMessage) then
            exit(false);
        ResponseMessage.Content.ReadAs(ResponseText);
        exit(ResponseMessage.IsSuccessStatusCode());
    end;

    procedure Connect(TenantId: Text; ClientId: Text; ClientSecret: SecretText)
    begin
        if not AcquireAccessToken(TenantId, ClientId, ClientSecret, AccessToken) then
            Error('Could not sign in to Business Central. Check the tenant, client ID and secret.');
        TokenAcquired := true;
    end;

    // AcquireAccessToken as shown above.
}

Format(CompanyId, 0, 4) writes the GUID without braces, which is what the URL needs. The $select keeps the reply small; ask only for the fields you will read.

The same thing in Ava

The quickest way to get this code right is to make the call work first, then generate the AL from it. In Ava, once a request returns what you expect, choose Code. Ava writes a procedure that takes var ResponseText: Text and returns Boolean, built from your method, URL, headers and body with HttpClient, HttpRequestMessage and HttpResponseMessage, with Content-Type on the content headers where it belongs. If the request signs in with OAuth2 client credentials, it adds an AcquireAccessToken(var AccessToken: SecretText) procedure for the token call. The same button gives you the cURL command for the request. Code generation is part of the Pro plan.

Sources