MSBA-353 · Lesson 3 of 12 · 24 min

Calling external services

▶ Video coming soon A video version of this lesson is on the way.

Wholesale orders leave the roastery by courier. Corbel & Finch ships cafés and grocers through a regional parcel carrier, which this course calls Tidewell Parcel, and until now Dovrin's team typed each shipment into Tidewell's website, printed the label and wrote the tracking number on the packing slip. Callum wanted two things from Business Central: a rate quote on the sales order before the customer confirms, and the tracking number stored on the posted shipment so customer service can answer "where is my coffee?" without opening another browser tab. Tidewell publishes a REST API with JSON requests and responses. In lesson 1, outside systems called Business Central; in this lesson Business Central calls out.

The MB-820 outline lists three skills under accessing external REST services: apply HTTP classes and their functions, get data from and send data to an external REST service, and create and parse JSON. A fourth skill from the API group belongs here too, because every outbound call needs a secret: protect sensitive data by using Isolated Storage.

The HTTP data types

AL has a small family of data types for HTTP. They are wrappers around the platform's HTTP stack, so the code runs the same in every Business Central online environment, with no .NET interop allowed or needed.

AL HTTP data types.
Data typeWhat it representsCommon methods
HttpClientThe object that sends requestsGet, Post, Put, Delete, Send, SetBaseAddress, DefaultRequestHeaders, Timeout, AddCertificate
HttpRequestMessageOne request: method, URI, headers and contentMethod, SetRequestUri, GetHeaders, Content
HttpResponseMessageThe replyIsSuccessStatusCode, HttpStatusCode, ReasonPhrase, Content, Headers
HttpHeadersA collection of headersAdd, Remove, Contains, GetValues, TryAddWithoutValidation
HttpContentA body, with its own content headersWriteFrom, ReadAs, GetHeaders

The simplest call uses the client's shortcut methods: Get with a URL, or Post with a URL and content. For anything that needs custom headers on one request, or a method such as PATCH, build an HttpRequestMessage and call Send. Each method returns a Boolean that is false only when the request could not be sent at all, for example when the host name does not resolve. A response with status 404 or 500 still returns true, so the code must check IsSuccessStatusCode or HttpStatusCode separately. That two-level check is the most common bug Noor sees in partner code.

A flow from left to right. An AL procedure builds a JSON object, writes it to HttpContent with a content-type header, adds it to an HttpRequestMessage with method POST and the rate URL, and sends it with HttpClient. Two checks follow: did Send return true, and is the status code successful. If both pass, the response content is read as text and parsed into a JsonObject. Failure branches lead to clear error messages.
Building, sending and checking an outbound request.

Calling the rate service

Tidewell's rate endpoint takes a POST with the origin and destination postal codes, the number of parcels and their weights, and returns a list of services with prices. Noor wrote a codeunit with a single public procedure that the sales order page calls.

Posting a JSON rate request and checking both levels of failure.
codeunit 50060 "CFR Tidewell Rate Client"
{
    Access = Internal;

    procedure GetCheapestRate(SalesHeader: Record "Sales Header"; TotalKg: Decimal; Parcels: Integer) Rate: Decimal
    var
        Client: HttpClient;
        Request: HttpRequestMessage;
        Response: HttpResponseMessage;
        Content: HttpContent;
        ContentHeaders: HttpHeaders;
        Body: JsonObject;
        ResponseText: Text;
    begin
        Body.Add('originPostal', GetRoasteryPostalCode());
        Body.Add('destinationPostal', SalesHeader."Ship-to Post Code");
        Body.Add('parcels', Parcels);
        Body.Add('totalWeightKg', TotalKg);

        Content.WriteFrom(Format(Body));
        Content.GetHeaders(ContentHeaders);
        ContentHeaders.Remove('Content-Type');
        ContentHeaders.Add('Content-Type', 'application/json');

        Request.Method := 'POST';
        Request.SetRequestUri(GetBaseUrl() + '/v2/rates');
        Request.Content := Content;
        AddAuthorization(Request);
        Client.Timeout := 20000;

        if not Client.Send(Request, Response) then
            Error(CannotReachErr);
        if not Response.IsSuccessStatusCode() then
            Error(ServiceErr, Response.HttpStatusCode(), Response.ReasonPhrase());

        Response.Content.ReadAs(ResponseText);
        Rate := ParseCheapestRate(ResponseText);
    end;

    var
        CannotReachErr: Label 'Business Central could not reach the Tidewell rate service. Check the connection and try again.';
        ServiceErr: Label 'The Tidewell rate service returned an error (%1 %2).', Comment = '%1 = status code, %2 = reason';
}

A few details in that listing matter. The content type is set on the content headers, not on the request headers, because it describes the body. The Timeout is set in milliseconds so a slow carrier cannot freeze the sales order page for long; the platform also enforces its own maximum. Error texts are labels so they can be translated, and they tell the user what to do rather than dumping a raw response. The codeunit is Access = Internal, so other extensions cannot call it and depend on its signature.

Creating and parsing JSON

AL's JSON types are JsonObject, JsonArray, JsonValue and JsonToken, where a token can be any of the other three. Objects are built with Add and read with Get, which returns a token, or with typed helpers such as GetText and GetDecimal in recent versions. SelectToken follows a JSON path expression, which is handy for nested data. Parsing a response starts with ReadFrom on a JsonObject or JsonArray, which returns false if the text is not valid JSON.

Reading an array of services and keeping the lowest price.
local procedure ParseCheapestRate(ResponseText: Text) Cheapest: Decimal
var
    Root: JsonObject;
    Services: JsonArray;
    ServiceToken: JsonToken;
    PriceToken: JsonToken;
    First: Boolean;
begin
    if not Root.ReadFrom(ResponseText) then
        Error(BadResponseErr);
    if not Root.SelectToken('$.services', ServiceToken) then
        Error(BadResponseErr);
    Services := ServiceToken.AsArray();
    First := true;
    foreach ServiceToken in Services do
        if ServiceToken.AsObject().Get('price', PriceToken) then
            if First or (PriceToken.AsValue().AsDecimal() < Cheapest) then begin
                Cheapest := PriceToken.AsValue().AsDecimal();
                First := false;
            end;
end;

The response Tidewell returns looks like the following. The parser walks the services array and compares prices; it does not assume that the cheapest service comes first, and it fails with a clear message if the structure is not what it expects.

A sample rate response.
{
  "quoteId": "Q-77120",
  "services": [
    { "code": "GROUND", "price": 18.40, "transitDays": 2 },
    { "code": "EXPRESS", "price": 31.75, "transitDays": 1 }
  ]
}

JSON numbers arrive as values that AL converts with AsDecimal or AsInteger; dates arrive as text and should be converted with Evaluate using the XML format so regional settings do not change the result. Missing properties are normal in real services, so every Get is checked. When Business Central sends JSON, Format on a JsonObject or WriteTo produce compact text; field names should match the service's contract exactly, including case.

Secrets and Isolated Storage

Tidewell issues an API key per customer account. It must not be hard-coded in the extension, typed into a normal table field anyone can export, or written to telemetry. Business Central provides Isolated Storage: a key-value store whose entries belong to the extension that wrote them, so no other extension can read them. Each entry has a DataScope: Module for the whole extension in the environment, Company for one company, User for one user, or CompanyAndUser for one user in one company.

Storing and reading an API key with company scope, kept as SecretText.
procedure SetApiKey(NewKey: SecretText)
begin
    IsolatedStorage.Set('TidewellApiKey', NewKey, DataScope::Company);
end;

local procedure AddAuthorization(var Request: HttpRequestMessage)
var
    Headers: HttpHeaders;
    ApiKey: SecretText;
begin
    if not IsolatedStorage.Get('TidewellApiKey', DataScope::Company, ApiKey) then
        Error(NoKeyErr);
    Request.GetHeaders(Headers);
    Headers.Add('X-Api-Key', ApiKey);
end;

The SecretText data type keeps the key out of reach of the debugger: a variable of that type cannot be inspected in a debugging session, and it can be passed to HTTP headers and content without being converted to ordinary text. The setup page that captures the key uses an ExtendedDatatype = Masked field and calls the procedure immediately, so the key never sits in a table. Isolated Storage also offers SetEncrypted for values that should be encrypted at rest. For Marketplace apps that need a publisher-owned secret shared across every customer, such as the publisher's own service key, Microsoft recommends the App Key Vault feature, which reads secrets from the publisher's Azure Key Vault at runtime.

Where each secret lives.
SecretOwnerWhere Noor stored it
Tidewell API keyCorbel & Finch's Tidewell accountIsolated Storage, Company scope
Web shop client secretWeb shop's Entra appThe web shop's own key vault, never in Business Central
Azure OpenAI key for lesson 4Corbel & Finch's Azure subscriptionIsolated Storage, Module scope
Quarrystone service key for a Marketplace appQuarrystoneApp Key Vault

Outbound calls in sandboxes

Sandboxes are copies of production, and an extension that calls a carrier from a sandbox could book real shipments. Business Central therefore blocks outbound HTTP from extensions in sandbox environments by default. An administrator allows it per extension in Extension Management, through the extension's settings and the Allow HttpClient Requests option. Noor turned it on in CONFIG with Tidewell's test endpoint configured, and wrote the base URL into the setup table so that production and sandboxes point at different addresses. When a sandbox is created as a copy of production after go-live, the setup must be checked before anyone tests, because the copied record will still point at the live carrier.

Worked problem

Storing the tracking number

When a wholesale shipment is posted, Business Central should book the shipment with Tidewell and store the returned tracking number on the posted shipment. If Tidewell is down at 4:55 p.m., the warehouse still needs to post and load the van. How should the call be designed?

Show solution
  1. Do not call Tidewell inside the posting transaction. An outbound call cannot be rolled back, and a slow call would hold locks while posting runs.
  2. Subscribe to the event raised after the shipment is posted and create a record in a CFR Shipment Booking queue table with status Pending.
  3. A job queue entry runs every five minutes, books pending shipments, writes the tracking number to the posted shipment's extension field and marks the record Booked.
  4. If Tidewell returns a server error or a timeout, the job leaves the record Pending and tries again next run; after three failures it marks it Failed and notifies the warehouse lead.

Answer: Decouple the outbound call from posting with a queue table and a job queue entry, so posting never waits for the carrier and failures are retried.

Reliability patterns

The example captures a general rule: never make an outbound call inside a write transaction unless the user is waiting for it and can retry. HTTP requests are not part of the database transaction, so if posting fails after the call, the external system has already acted. Use a commit boundary, a queue table or a job queue entry instead.

Retries should apply only to errors that might go away: timeouts, 429 throttling and 5xx server errors. A 400 or 401 means the request or key is wrong, and retrying only produces more failures. Each retry should wait longer than the last. Where the service supports an idempotency key, send one, so that a retried booking does not create two shipments. For long-running work or libraries AL cannot run, such as image processing, partners often build an Azure Function that the extension calls; the same HTTP and secret rules apply.

Every outbound request also produces telemetry. Business Central logs outgoing web service calls as event RT0019 with the endpoint, status and duration, in the environment's Application Insights resource and in the app publisher's resource. Lesson 7 shows how Noor used that signal to find that rate quotes for northern postal codes were slow.

A setup page and the Service Connections list

Every integration needs a home for its settings. Noor created a CFR Tidewell Setup table with a single record holding the base URL, the account number, a test-mode flag, the default service code and the number of retries, and a setup page over it. The API key field on the page is not a table field at all: it is a page variable with ExtendedDatatype = Masked whose OnValidate trigger passes the value straight to Isolated Storage and then clears it, and a read-only field shows only whether a key has been stored.

Users should be able to find the setup without knowing its page name. Business Central has a Service Connections page that lists every external connection in the company, with its status. An extension adds itself by subscribing to the event that the page raises when it collects connections and inserting a line that points at its setup page. Noor also registered the setup as an assisted setup through the guided experience module, so that a new administrator in a fresh environment is walked through entering the URL, account and key, and testing the connection, in a few steps instead of hunting for fields.

The same extension, configured differently per environment.
SettingCONFIG and sandboxesPROD after go-live
Base URLTidewell test endpointTidewell live endpoint
Account numberTest account issued by TidewellCorbel & Finch wholesale account
Test modeOn: labels marked as samplesOff
Allow HttpClient RequestsTurned on by the admin for the extensionNot needed; production allows outbound calls
API keyTest key in Isolated StorageLive key entered by Callum after go-live

Logging calls without leaking data

When customer service asks why a booking failed, "it returned an error" is not an answer. Noor added a CFR Integration Log table: one row per outbound call, with the date and time, the user or job that made it, the endpoint path without query parameters, the HTTP method, the status code, the duration in milliseconds, a short error summary and the related document number. The full request and response bodies are not stored by default; a Debug Logging setting, off in production, keeps them for one day when a problem is being investigated. A job queue entry deletes log rows older than 60 days, because a log that grows without limit becomes its own performance problem.

The log must never contain the API key, so the header that carries it is never written anywhere. The customer's address and postal code are personal or business data, so the bodies, when logged, are classified as customer content and kept only briefly. Every field in the log table has a DataClassification value, which lesson 10 shows is a requirement for Marketplace apps and a good habit everywhere. Telemetry follows the same rule: the outgoing request signal records the endpoint and status, and any custom telemetry Noor adds carries document numbers but no addresses.

Data leaving Business Central

An outbound integration is also a privacy decision. Before go-live, Callum listed what data leaves Business Central for Tidewell: ship-to name, address and postal code, parcel count and weight, and the order number used as a reference. Bettina confirmed that the courier contract covers that data. Microsoft's own integrations that send data outside the Business Central compliance boundary ask an administrator to accept a privacy notice first; a partner extension cannot rely on that mechanism for its own services, so the agreement with the carrier and the customer's instructions are what matter. Noor's rule for the code was simple: send only the fields the service needs, and never send a whole record "in case it is useful".

Worked problem

Diagnosing a failed rate quote

Callum reports that the Get Rate action on a sales order for a grocer in a new delivery area shows "The Tidewell rate service returned an error (400 Bad Request)." What does Noor check, in order?

Show solution
  1. Open the integration log for the order: status 400, duration 180 ms, error summary "destinationPostal invalid".
  2. A 400 is a client error, so retrying is pointless; the request itself is wrong.
  3. The ship-to address on the order has the postal code typed with a lowercase letter and no space, which Tidewell rejects.
  4. Fix the data and add normalization in the codeunit: trim, convert to uppercase and apply the expected format before sending.

Answer: Use the log to read the status and error, treat 4xx as a data or request problem rather than a transient failure, and normalize inputs before sending.

Common mistakes

  • MistakeTreating a true result from Send as success.

    InsteadCheck IsSuccessStatusCode or HttpStatusCode as well; Send is false only when the request could not be sent.

  • MistakePutting the content type on the request headers.

    InsteadSet Content-Type on the content headers, which describe the body.

  • MistakeHard-coding an API key or storing it in a normal field.

    InsteadStore it in Isolated Storage as SecretText, or in App Key Vault for publisher secrets.

  • MistakeCalling an external service inside posting.

    InsteadQueue the work and call after commit, with retries for transient errors.

  • MistakeCopying production to a sandbox and testing at once.

    InsteadCheck service URLs and keep outbound calls blocked until test endpoints are set.

Summary and key terms

  • HttpClient sends requests; HttpRequestMessage, HttpResponseMessage, HttpHeaders and HttpContent describe them.
  • Check both whether a request was sent and whether its status code succeeded.
  • JsonObject, JsonArray, JsonValue and JsonToken build and parse JSON; check every Get and ReadFrom.
  • Isolated Storage keeps secrets per extension with Module, Company, User or CompanyAndUser scope; SecretText hides values from the debugger.
  • Sandboxes block outbound HTTP from extensions until Allow HttpClient Requests is turned on.
  • Keep external calls out of posting transactions; queue them and retry only transient failures.
HttpClient
The AL data type that sends HTTP requests and receives responses.
HttpContent
The body of a request or response, with its own content headers.
JsonToken
A JSON element that can be an object, an array or a value.
Isolated Storage
A per-extension key-value store for sensitive values, with data scopes.
SecretText
A data type for secrets that cannot be inspected in the debugger.
App Key Vault
A feature that lets Marketplace apps read publisher secrets from Azure Key Vault.
Idempotency key
A request identifier that stops a retried call from being processed twice.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Send returned true but the carrier replied 503. What happened and what should the code do?

    Show answer

    The request was delivered but the service failed; the code should treat it as a transient error and retry later with back-off.

  2. Why is the API key stored with Company scope?

    Show answer

    Because the Tidewell account belongs to the company; another company in the same environment could have its own key.

  3. Why is booking with Tidewell done by a job queue entry rather than during posting?

    Show answer

    So posting never waits for or depends on the carrier, and failed bookings can be retried.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz