MSBA-359 · Lesson 6 of 12 · 21 min

Domain review: integration

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

The integration area was where the November update moved the most weight, and it was also where Joss had the most real experience. He had written the JSON parser for the Tidewell Parcel rate quotes, the read-only coffeeAvailability API for the web shop, and two of the tests for the café transfer draft. "Which is exactly the danger," Noor told him. "You know how we did it. The exam asks how it should be done in general, and it will offer you options that look like our shortcuts." They spent the session going through each bullet, asking each time what the general rule was and where Quarrystone's code had been a special case.

Integrate Business Central with other applications is worth 15 to 20 percent, up from the previous outline. It has three groups: accessing external REST services, implementing APIs by using AL, and the new Build Copilot capability by using AL.

A diagram with Business Central in the centre. On the right, outbound calls from AL through HttpClient to an external REST service, with JSON parsed on return and secrets read from Isolated Storage. On the left, inbound calls from a web shop and Power Platform to API pages and API queries, with bound and unbound actions, and Read Scale-Out sending read-only traffic to a replica. At the bottom, Copilot capabilities call Azure OpenAI through the AI module, and agents act as users with their own permissions.
The three integration groups: calling out, letting others call in, and Copilot.

Calling external REST services

AL calls web services with a small family of types. An HttpClient sends requests. An HttpRequestMessage carries the method, the URI, the headers and the HttpContent. An HttpResponseMessage returns the status, headers and content. For a simple GET, HttpClient.Get(Url, Response) is enough; for anything with a body or custom headers, build a request message and call Send. The return value of Get and Send is a Boolean that says whether the call reached the server at all; it does not say whether the server liked the request. Always check Response.IsSuccessStatusCode and Response.HttpStatusCode separately, because a 404 or 500 is still a successful call in transport terms.

Posting JSON to a REST service and checking both the transport result and the status code.
procedure GetRates(Request: JsonObject) Result: JsonObject
var
    Client: HttpClient;
    Msg: HttpRequestMessage;
    Content: HttpContent;
    ContentHeaders: HttpHeaders;
    Response: HttpResponseMessage;
    Body: Text;
begin
    Request.WriteTo(Body);
    Content.WriteFrom(Body);
    Content.GetHeaders(ContentHeaders);
    ContentHeaders.Remove('Content-Type');
    ContentHeaders.Add('Content-Type', 'application/json');

    Msg.Method := 'POST';
    Msg.SetRequestUri(GetBaseUrl() + '/rates');
    Msg.Content := Content;
    AddAuthorization(Msg);

    if not Client.Send(Msg, Response) then
        Error(NoConnectionErr);
    if not Response.IsSuccessStatusCode() then
        Error(ServiceErr, Response.HttpStatusCode());

    Response.Content.ReadAs(Body);
    Result.ReadFrom(Body);
end;

Content headers belong to the HttpContent, not to the request; request headers such as authorization belong to the request message. Getting that wrong is a classic code-reading trap. Timeouts are set on the client with Client.Timeout. In sandboxes, outbound HTTP calls from extensions are blocked until an administrator allows them for the extension in Extension Management with the Allow HttpClient Requests setting, so that a sandbox copied from production does not call live services by accident. Outgoing calls are recorded in telemetry with event ID RT0019.

Creating and parsing JSON

AL's JSON types are JsonObject, JsonArray, JsonValue and the general JsonToken, which can hold any of them. ReadFrom parses text; WriteTo serializes. Get retrieves a property as a token; SelectToken takes a JSONPath such as $.services[0].price; AsValue, AsObject and AsArray convert tokens; and a JsonValue converts with AsDecimal, AsText, AsBoolean, AsDate and so on. Building JSON is the reverse: Add properties to an object, Add objects to an array, then WriteTo.

Parsing an array of services and returning the lowest price.
local procedure CheapestPrice(Body: Text) Cheapest: Decimal
var
    Root: JsonObject;
    Services: JsonToken;
    Service: JsonToken;
    Price: JsonToken;
    First: Boolean;
begin
    Root.ReadFrom(Body);
    Root.Get('services', Services);
    First := true;
    foreach Service in Services.AsArray() do begin
        Service.AsObject().Get('price', Price);
        if First or (Price.AsValue().AsDecimal() < Cheapest) then
            Cheapest := Price.AsValue().AsDecimal();
        First := false;
    end;
end;

Implementing APIs

Business Central publishes standard APIs (version v2.0) for common entities such as customers, items and sales orders, and developers add their own with API pages and API queries. An API page has PageType = API and the properties APIPublisher, APIGroup, APIVersion, EntityName and EntitySetName, which together form its URL: /api/publisher/group/version/companies(id)/entitySetName. Good practice is to use SystemId as the key through ODataKeyFields, set DelayedInsert = true so a record is inserted only after all fields in the request are set, and use camelCase field names. An API query, with QueryType = API, gives a read-only endpoint over joined and aggregated data.

A read-only warranty registration API, modelled on the one built for the web shop in MSBA-352.
page 50110 "CNF Warranty Registration API"
{
    PageType = API;
    APIPublisher = 'quarrystone';
    APIGroup = 'warranty';
    APIVersion = 'v1.0';
    EntityName = 'warrantyRegistration';
    EntitySetName = 'warrantyRegistrations';
    SourceTable = "CNF Warranty Registration";
    ODataKeyFields = SystemId;
    DelayedInsert = true;
    Editable = false;
    DataAccessIntent = ReadOnly;

    layout
    {
        area(Content)
        {
            repeater(Records)
            {
                field(id; Rec.SystemId) { }
                field(number; Rec."No.") { }
                field(serialNumber; Rec."Serial No.") { }
                field(endDate; Rec."End Date") { }
                field(status; Rec.Status) { }
            }
        }
    }
}

Bound actions are procedures on an API page that act on one entity, such as releasing an order or voiding a registration. The procedure has the [ServiceEnabled] attribute and a WebServiceActionContext parameter used to report the result, and clients call it with a POST to the entity URL followed by /Microsoft.NAV.actionName. Unbound actions are not tied to an entity: they are public procedures in a codeunit published as a web service, called with a POST to the OData V4 endpoint named after the service and procedure. Use a bound action when the operation belongs to a record, and an unbound action for a general operation, such as recalculating all warranty end dates.

Read Scale-Out sends read-only work to a read-only replica of the database, so heavy reads do not compete with users entering data. Setting DataAccessIntent = ReadOnly on an API page, API query, report or query asks for the replica; a client can also request it for a call with the Data-Access-Intent: ReadOnly header. A ReadOnly object cannot write: any insert or modify fails. That is why the warranty API above is also Editable = false. Business Central online applies operational limits to web service calls, such as limits on request rates per user, and returns HTTP 429 when a client sends too many; well-behaved clients back off and retry.

Protecting sensitive data with Isolated Storage

Secrets such as API keys and passwords should never sit in code, labels or ordinary table fields. Isolated Storage is a key-value store isolated per extension, so other extensions cannot read it. The DataScope of each value is Module (the whole extension), Company, User or CompanyAndUser. Set and Get store and read values; SetEncrypted encrypts the value at rest; Contains and Delete complete the set. Read secrets into a SecretText variable, which the debugger cannot display and which can be passed to HTTP headers without being converted to plain text. For Marketplace apps that need a publisher secret shared by every customer, Microsoft recommends the App Key Vault feature, which reads it from the publisher's Azure Key Vault at runtime.

Building Copilot capability

The new group has three bullets: build Copilot capability, build Copilot user experiences and create agents. MSBA-353 built Corbel & Finch's "Draft café transfer" feature, and its parts map exactly onto the first two bullets.

A Copilot capability is registered so administrators can see and control it. The developer adds a value to the Copilot Capability enum with an enum extension and registers it with the Copilot Capability codeunit, normally from an install codeunit (and an upgrade codeunit for existing installations), with an availability of Preview or Generally Available, a learn-more URL and a billing type. Administrators see capabilities on the Copilot & agent capabilities page and can switch them off without uninstalling the app.

Copilot billing types for partner capabilities.
Billing typeAzure OpenAI resource usedWho pays
Microsoft BilledBusiness Central's own AI resourcesThe customer, through Copilot credits
Custom BilledThe partner's own resourceThe customer pays the partner as agreed
Not BilledThe partner's or customer's own resourceWhoever owns the resource pays Azure directly

The model call goes through the AI module of the System Application. The Azure OpenAI codeunit is authorized for an endpoint and deployment (or Business Central's managed resources when allowed), tied to the capability with SetCopilotCapability, and called with GenerateChatCompletion. AOAI Chat Messages holds the system message (the metaprompt) and user messages; AOAI Chat Completion Params sets limits such as maximum tokens and temperature; AOAI Operation Response reports success and errors. The AI module also supports function calling, where the model asks AL to run a named function. If code calls the model with a capability that is not registered, the call fails.

Good Copilot features follow responsible AI practice. Ground the prompt in real Business Central data, so the model does not invent items or customers. Ask for structured output, such as JSON, and validate it in AL before showing it, dropping anything that does not match real records. Keep a human in the loop: the user reviews and accepts the proposal before anything is written. Test with realistic and adversarial inputs, including text that tries to override the instructions.

Copilot user experiences

The standard Copilot experience is a page with PageType = PromptDialog. It has three modes: Prompt, where the user types into fields in area(Prompt) and optional area(PromptOptions); Generate, while the code calls the model; and Content, where the proposal appears in area(Content). System actions in area(SystemActions) provide the standard buttons, such as Generate, Regenerate, OK and Cancel, which developers can caption. The platform adds the AI-generated content notice and feedback controls. The dialog is opened from an action placed in the Prompting area of a page's actions, which the client shows with the Copilot icon. IsPreview = true shows a preview label to match a Preview capability.

Creating agents

An agent is different from a Copilot dialog. It is a Business Central user that performs tasks on its own, through the same pages and permissions as a person, and asks a human for review or help where configured. Microsoft's own agents, such as the Sales Order Agent and the Payables Agent, are examples. Partners build their own with the Agent SDK for AL, which was in preview in November 2026: it became available for sandbox evaluation in version 27.4 and production use from version 28.1.

Building blocks of the Agent SDK for AL (preview).
Building blockPurpose
Agent type (enum extension)Registers a new kind of agent
IAgentFactory interfaceCreates and configures agent instances, defaults and setup
IAgentMetadata interfaceSupplies metadata such as initials and the setup and summary pages
IAgentTaskExecution interfaceControls how tasks are processed and when to ask a user
Configuration dialog pageThe setup experience for an agent instance
InstructionsNatural-language guidance for what the agent should do
TasksUnits of work created from page actions, business events or messages such as email

Agents work through permissions like any user: an agent can do only what its permission sets allow, and administrators assign them. That is the main control. Because agents act without a person clicking each step, design them with narrow permissions, clear instructions, review points for anything risky, and telemetry. In Visual Studio Code, the AL: New Project command offers an agent template. Corbel & Finch has not deployed a custom agent; Quarrystone built only a sandbox demonstration in MSBA-353, and the company's first agent decision, on the Payables Agent, is planned for March 2027.

Because the SDK was in preview, remember the study guide's note: most questions cover generally available features, but commonly used preview features may appear. Expect questions on the concepts, such as what an agent is, how it is controlled by permissions and what the main interfaces do, rather than on details likely to change before general availability.

Standard APIs, custom APIs and authentication

Before building a custom API page, check whether the standard API v2.0 already covers the entity. Customers, vendors, items, sales and purchase documents, journals and many more are available, documented and maintained by Microsoft. Custom APIs are for your own tables, for fields the standard API lacks, or for a shape that suits one integration, such as the read-only coffee availability endpoint built for Corbel & Finch's web shop. A custom API should have its own publisher and group so it never collides with Microsoft's, and a version that you increase when you make breaking changes, leaving the old version working until clients move.

External systems authenticate with Microsoft Entra ID using OAuth. For a system that runs without a user, such as a nightly import, the usual pattern is service-to-service authentication: an app registration in Microsoft Entra ID, registered in Business Central on the Microsoft Entra Applications page, with permission sets granted to that application rather than to a person. Older approaches based on web service access keys belong to the past for online environments; if an option relies on them, treat it with suspicion.

For systems that need to know when data changes, Business Central supports webhooks on API v2.0 and on custom API pages. A client creates a subscription, Business Central validates it with a handshake, and from then on it sends notifications when records change. Subscriptions expire after three days unless renewed, notifications are collapsed over a short period, and a large burst of changes arrives as a single collection notification telling the client to read the changes itself. Not every resource supports webhooks: temporary tables, tables with composite keys, system tables and API queries are among the exceptions.

Worked problem

Inbound, outbound or Copilot?

Four requirements: (1) a delivery service must push status updates into Business Central; (2) Business Central must fetch exchange rates each morning from a bank's REST service; (3) Power BI must read large volumes of sales data without slowing users; (4) sales staff want a draft customer email summarizing overdue invoices, which they edit before sending.

Show solution
  1. (1) Inbound: a custom API page, or a bound action on one, with an Entra app for the service and its own permission set.
  2. (2) Outbound: a job queue entry running a codeunit that uses HttpClient, with the bank key in Isolated Storage read as SecretText.
  3. (3) Inbound read: an API query or API page with DataAccessIntent = ReadOnly, so reads use the replica.
  4. (4) Copilot: a registered capability, a PromptDialog page grounded in the customer's open entries, with the user reviewing before sending.

Answer: Decide first who starts the conversation. If an outside system calls in, build APIs; if Business Central calls out, use HttpClient; if a model generates a proposal for a person, build a Copilot capability.

Common mistakes

  • MistakeTreating Send returning true as success.

    InsteadAlso check IsSuccessStatusCode; Send only reports that a response arrived.

  • MistakeAdding Content-Type to the request headers.

    InsteadContent headers belong to HttpContent.GetHeaders.

  • MistakeWriting from an object with DataAccessIntent = ReadOnly.

    InsteadRead-only objects run on the replica and cannot write.

  • MistakeStoring an API key in a label or setup field.

    InsteadUse Isolated Storage and SecretText; App Key Vault for publisher secrets.

  • MistakeLetting model output post or modify data directly.

    InsteadValidate the output and have a person accept it first.

Summary and key terms

  • HttpClient, HttpRequestMessage, HttpContent and HttpResponseMessage call REST services; check both the call and the status code.
  • JsonObject, JsonArray, JsonToken and JsonValue parse and build JSON with ReadFrom, Get, SelectToken and WriteTo.
  • API pages and queries define versioned endpoints; bound actions act on an entity; unbound actions are codeunit procedures.
  • Read Scale-Out uses DataAccessIntent = ReadOnly; Isolated Storage with SecretText protects secrets.
  • Copilot capabilities are registered with an availability and billing type and use the AI module; PromptDialog pages provide the experience.
  • Agents are users that perform tasks under permissions; the Agent SDK for AL was in preview in November 2026.
API page
A page with PageType = API that exposes an entity through a versioned REST endpoint.
Bound action
A ServiceEnabled procedure on an API page called on one entity.
Unbound action
A codeunit procedure published as an OData web service operation.
Read Scale-Out
Routing read-only work to a database replica using DataAccessIntent = ReadOnly.
Isolated Storage
A per-extension key-value store with Module, Company, User and CompanyAndUser scopes.
Copilot capability
A registered AI feature with availability and billing type that administrators can switch off.
PromptDialog
The page type for Copilot experiences, with Prompt, Generate and Content modes.

Practice problems

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

  1. What does HttpClient.Send returning false mean?

    Show answer

    The request did not get a response, for example a connection failure.

  2. Which property routes an API query to the replica?

    Show answer

    DataAccessIntent = ReadOnly.

  3. Which DataScope keeps a value per user across companies?

    Show answer

    User.

  4. Where do administrators switch off a partner Copilot feature?

    Show answer

    On the Copilot & agent capabilities page.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz