Exercise: Integrate Business Central with a REST service

Completed

In this exercise, you build an AL extension that creates and retrieves resources through a public REST test endpoint. You also test an HTTP failure and a response that contains valid JSON but omits a required property.

Prepare the sandbox and project

You need a Business Central online sandbox, Visual Studio Code with the AL Language extension, permission to publish and configure the sample extension, and approved access to the public endpoint.

The sample uses https://jsonplaceholder.typicode.com/posts, which accepts test GET and POST requests without an account or credentials. This mock posts API demonstrates a fulfillment-shaped request; it isn't a real order-processing system. Writes are simulated, so you can't retrieve a created resource later. Echoed fields don't prove fulfillment, and simulated writes don't prevent the service from processing or logging submitted data.

Important

Don’t send business, personal, confidential, or production data to the test endpoint. Use only the sample values in this exercise.

The 45-minute estimate assumes the sandbox, permissions, symbols, and service are ready. The public service can be unavailable, throttled, or changed; setup and service delays can add time.

  1. In Visual Studio Code, run AL: Go! from the command palette to create a new exercise project for your sandbox. Verify that the generated platform, application, and runtime settings are compatible with the sandbox.

  2. Run AL: Download Symbols against the target sandbox if compatible symbols aren't already available.

  3. In app.json, add an object range that includes IDs 71200 through 71249 after confirming that the range is available. Preserve existing ranges, the project's unique app ID, metadata, compatible version fields, and other settings.

  4. Delete only the generated sample AL object from this new exercise project; don't remove existing application objects.

  5. Create files named FulfillmentRestClient.Codeunit.al and RestIntegrationTest.Page.al.

A production extension stores its endpoint and authentication configuration outside the codeunit.

Create the REST client codeunit

Add the following code to FulfillmentRestClient.Codeunit.al.

codeunit 71200 "Fulfillment REST Client"
{
    procedure CreateOrder(
        ExternalOrderNo: Code[20]; Description: Text[100]; Quantity: Decimal) ResultText: Text
    var
        Client: HttpClient;
        Content: HttpContent;
        ContentHeaders: HttpHeaders;
        Response: HttpResponseMessage;
        RequestBody: JsonObject;
        RequestText: Text;
        ResponseText: Text;
        ExternalId: Integer;
    begin
        RequestBody.Add('userId', 1);
        RequestBody.Add('title', ExternalOrderNo);
        RequestBody.Add('body', Description);
        RequestBody.Add('quantity', Quantity);
        RequestBody.WriteTo(RequestText);

        Content.WriteFrom(RequestText);
        Content.GetHeaders(ContentHeaders);
        if ContentHeaders.Contains('Content-Type') then
            ContentHeaders.Remove('Content-Type');
        ContentHeaders.Add('Content-Type', 'application/json');

        if not Client.Post(PostsEndpointLbl, Content, Response) then
            Error(TransportErr);

        Response.Content().ReadAs(ResponseText);
        EnsureSuccessfulResponse(Response, ResponseText);

        ExternalId := ReadRequiredId(ResponseText);
        ResultText := StrSubstNo(
            'POST succeeded. Status: %1. External ID: %2. Response: %3',
            Response.HttpStatusCode(), ExternalId, ResponseText);
    end;

    procedure GetOrder(PostId: Integer) ResultText: Text
    var
        Client: HttpClient;
        Response: HttpResponseMessage;
        ResponseText: Text;
        Endpoint: Text;
        ExternalId: Integer;
    begin
        Endpoint := StrSubstNo('%1/%2', PostsEndpointLbl, PostId);

        if not Client.Get(Endpoint, Response) then
            Error(TransportErr);

        Response.Content().ReadAs(ResponseText);
        EnsureSuccessfulResponse(Response, ResponseText);

        ExternalId := ReadRequiredId(ResponseText);
        ResultText := StrSubstNo(
            'GET succeeded. Status: %1. External ID: %2. Response: %3',
            Response.HttpStatusCode(), ExternalId, ResponseText);
    end;

    procedure GetOrdersForUser(UserId: Integer) ResultText: Text
    var
        Client: HttpClient;
        Response: HttpResponseMessage;
        ResponseText: Text;
        Endpoint: Text;
        FirstExternalId: Integer;
        OrderCount: Integer;
    begin
        Endpoint := StrSubstNo('%1?userId=%2', PostsEndpointLbl, UserId);

        if not Client.Get(Endpoint, Response) then
            Error(TransportErr);

        Response.Content().ReadAs(ResponseText);
        EnsureSuccessfulResponse(Response, ResponseText);

        ReadOrderArray(ResponseText, OrderCount, FirstExternalId);
        ResultText := StrSubstNo(
            'GET collection succeeded. Status: %1. Count: %2. First external ID: %3.',
            Response.HttpStatusCode(), OrderCount, FirstExternalId);
    end;

    [TryFunction]
    procedure TryValidateResponse(ResponseText: Text)
    var
        ExternalId: Integer;
    begin
        ExternalId := ReadRequiredId(ResponseText);
    end;

    local procedure EnsureSuccessfulResponse(
        Response: HttpResponseMessage; ResponseText: Text)
    begin
        if Response.IsSuccessStatusCode() then
            exit;

        Error(
            ServiceErr,
            Response.HttpStatusCode(),
            Response.ReasonPhrase(),
            CopyStr(ResponseText, 1, 250));
    end;

    local procedure ReadRequiredId(ResponseText: Text) ExternalId: Integer
    var
        ResponseObject: JsonObject;
        IdToken: JsonToken;
    begin
        if not ResponseObject.ReadFrom(ResponseText) then
            Error(InvalidJsonErr, CopyStr(ResponseText, 1, 250));

        if not ResponseObject.Get('id', IdToken) then
            Error(MissingIdErr, CopyStr(ResponseText, 1, 250));

        if not IdToken.IsValue() then
            Error(InvalidIdErr, CopyStr(ResponseText, 1, 250));

        ExternalId := IdToken.AsValue().AsInteger();
    end;

    local procedure ReadOrderArray(
        ResponseText: Text; var OrderCount: Integer; var FirstExternalId: Integer)
    var
        Orders: JsonArray;
        FirstOrderToken: JsonToken;
        FirstOrder: JsonObject;
        IdToken: JsonToken;
    begin
        if not Orders.ReadFrom(ResponseText) then
            Error(InvalidArrayErr, CopyStr(ResponseText, 1, 250));

        OrderCount := Orders.Count();
        if OrderCount = 0 then
            Error(EmptyArrayErr);

        Orders.Get(0, FirstOrderToken);
        if not FirstOrderToken.IsObject() then
            Error(InvalidArrayItemErr);

        FirstOrder := FirstOrderToken.AsObject();
        if not FirstOrder.Get('id', IdToken) or not IdToken.IsValue() then
            Error(MissingArrayIdErr, CopyStr(ResponseText, 1, 250));

        FirstExternalId := IdToken.AsValue().AsInteger();
    end;

    var
        PostsEndpointLbl: Label 'https://jsonplaceholder.typicode.com/posts', Locked = true;
        TransportErr: Label 'The Business Central platform could not complete the REST request. Check the endpoint, network, certificate, timeout, and Allow HttpClient Requests setting.';
        ServiceErr: Label 'The service returned status %1 (%2). Response: %3';
        InvalidJsonErr: Label 'The service response is not valid JSON. Response: %1';
        MissingIdErr: Label 'The service response does not contain the required id property. Response: %1';
        InvalidIdErr: Label 'The id property is not a JSON value. Response: %1';
        InvalidArrayErr: Label 'The service response is not a valid JSON array. Response: %1';
        EmptyArrayErr: Label 'The service returned an empty order array.';
        InvalidArrayItemErr: Label 'The first order array item is not a JSON object.';
        MissingArrayIdErr: Label 'The first order array item does not contain a valid id. Response: %1';
}

The codeunit performs the following responsibilities:

  • CreateOrder builds a JSON body, sets its content type, sends a POST request, and validates the response.

  • GetOrder sends a GET request for a supplied resource ID.

  • GetOrdersForUser sends a filtered GET request, parses the returned JsonArray, and reads an id from its first JsonObject.

  • EnsureSuccessfulResponse reports an unsuccessful HTTP status with a bounded excerpt of the synthetic test response.

  • ReadRequiredId and ReadOrderArray treat malformed or incomplete payloads as contract failures.

Create the test page

Add the following code to RestIntegrationTest.Page.al.

page 71201 "REST Integration Test"
{
    PageType = Card;
    ApplicationArea = All;
    UsageCategory = Tasks;
    Caption = 'REST Integration Test';

    layout
    {
        area(Content)
        {
            group(Request)
            {
                Caption = 'Request';

                field(ExternalOrderNo; ExternalOrderNo)
                {
                    ApplicationArea = All;
                    Caption = 'External Order No.';
                }
                field(Description; Description)
                {
                    ApplicationArea = All;
                    Caption = 'Description';
                }
                field(Quantity; Quantity)
                {
                    ApplicationArea = All;
                    Caption = 'Quantity';
                    MinValue = 0;
                }
                field(PostId; PostId)
                {
                    ApplicationArea = All;
                    Caption = 'Post ID';
                    MinValue = 1;
                }
                field(UserId; UserId)
                {
                    ApplicationArea = All;
                    Caption = 'User ID';
                    MinValue = 1;
                }
            }
            group(Outcome)
            {
                Caption = 'Outcome';

                field(ResultText; ResultText)
                {
                    ApplicationArea = All;
                    Caption = 'Result';
                    Editable = false;
                    MultiLine = true;
                }
            }
        }
    }

    actions
    {
        area(Processing)
        {
            action(CreateOrder)
            {
                ApplicationArea = All;
                Caption = 'Create order';
                Image = New;

                trigger OnAction()
                begin
                    ResultText := RestClient.CreateOrder(
                        ExternalOrderNo, Description, Quantity);
                end;
            }
            action(GetOrder)
            {
                ApplicationArea = All;
                Caption = 'Get order';
                Image = Find;

                trigger OnAction()
                begin
                    ResultText := RestClient.GetOrder(PostId);
                end;
            }
            action(GetOrderList)
            {
                ApplicationArea = All;
                Caption = 'Get order list';
                Image = List;

                trigger OnAction()
                begin
                    ResultText := RestClient.GetOrdersForUser(UserId);
                end;
            }
            action(TestMissingProperty)
            {
                ApplicationArea = All;
                Caption = 'Test missing property';
                Image = TestDatabase;

                trigger OnAction()
                var
                    MissingIdResponse: Text;
                begin
                    MissingIdResponse :=
                        '{"userId":1,"title":"Response without an identifier"}';

                    if RestClient.TryValidateResponse(MissingIdResponse) then
                        ResultText := 'Unexpected success.'
                    else
                        ResultText := GetLastErrorText();
                end;
            }
        }
    }

    trigger OnOpenPage()
    begin
        ExternalOrderNo := 'SO-1001';
        Description := 'Sample fulfillment request';
        Quantity := 2;
        PostId := 1;
        UserId := 1;
    end;

    var
        RestClient: Codeunit "Fulfillment REST Client";
        ExternalOrderNo: Code[20];
        Description: Text[100];
        Quantity: Decimal;
        PostId: Integer;
        UserId: Integer;
        ResultText: Text[2048];
}

The page provides four controlled paths. Create order sends a POST request. Get order retrieves one object. Get order list retrieves and parses an array. Test missing property passes a supplied JSON payload directly to the response validator and captures the contract error without making an external call.

The sample checks JSON structure but leaves primitive conversion errors to the AL runtime; IsValue doesn't validate an integer contract. The Text[2048] result field and raw-response display are for the supplied synthetic examples, not general-purpose production use.

Publish and allow the request

  1. Build the project with AL: Package, resolve any compilation errors, and publish it to the sandbox with AL: Publish.

  2. In Business Central, search for and open Extension Management.

  3. Select the exercise extension, and then select Configure.

  4. Turn on Allow HttpClient Requests.

  5. Search for and open REST Integration Test.

If the extension is republished under a different app identity, confirm the setting again. The setting belongs to the installed extension.

Test the success and failure cases

Complete each test and record the observed result, even if it differs from the expected outcome. For discrepancies, check the request, outbound permission, service contract, and platform message. A failed action can leave an earlier value in the Result field; record the error dialog instead.

  1. Keep the supplied order values and select Create order. Confirm that the result reports status 201 and includes a returned id value.

  2. Set Post ID to 1, and then select Get order. Confirm that the result reports status 200 and the returned id is 1.

  3. Keep User ID set to 1, and then select Get order list. Confirm that the result reports status 200, the array count, and the first returned id.

  4. Set Post ID to 999999, and then select Get order. Record the HTTP status, reason phrase, and response excerpt shown by the error.

  5. Select Test missing property. Confirm that the result identifies the missing id property and retains the supplied response text.

  6. Record the sample extension's Allow HttpClient Requests setting, turn it off for this extension only, and repeat a GET request. Record the actual platform message; the runtime might block the call before the sample's custom transport error appears. A blocked request has no service HTTP status. Compare it with the missing-resource HTTP response, then restore the original setting.

Use the supplied existing ID for retrieval, not the ID returned by the simulated POST.

Record the integration evidence

Create a short integration test record with one row for each case.

Case Expected outcome Evidence to record
Create Successful POST Platform result, HTTP status, returned id, and parsed response.
Retrieve Successful GET Platform result, HTTP status, requested id, and parsed response.
Retrieve collection Successful GET HTTP status, JSON array count, and first parsed id.
Missing resource HTTP failure HTTP status, reason phrase, and response excerpt.
Missing property JSON contract failure Property name and retained response excerpt.
Blocked outbound call Platform failure Runtime message and extension setting that resolves it.

Your extension meets the exercise success criteria when it exchanges the expected payloads, checks the transport result before reading the response, validates HTTP status before accepting the payload, rejects the supplied incomplete payload, and contains no endpoint credentials in source code.

The missing-property test must report a contract failure; don't modify its fixture to make it succeed.