Exercise: Implement a secure Business Central API

Completed

In this exercise, you build and publish a customer integration surface. You create a writable API page, a read-only API query, a bound action, an unbound action, explicit permissions, and a company-scoped secret store.

Prepare the sandbox and project

You need a Business Central online sandbox, Visual Studio Code with the AL Language extension, permission to publish extensions, permission to publish a codeunit on the Web Services page, and an OAuth access token that can call the sandbox APIs.

  1. Create an AL project for the sandbox by running AL: Go! from the command palette.
  2. Download symbols when prompted.
  3. Set the app.json object range to include IDs 71300 through 71349.
  4. Delete the generated sample object.
  5. Create six AL files for the objects supplied in this exercise.

Use sample CRONUS data. Don't place an access token or real integration credential in an AL file or a request file that enters source control.

Implement the API page and bound action

Create IntegrationCustomerAPI.Page.al with the following code.

page 71300 "Integration Customer API"
{
    PageType = API;
    APIPublisher = 'training';
    APIGroup = 'integration';
    APIVersion = 'v1.0';
    EntityName = 'integrationCustomer';
    EntitySetName = 'integrationCustomers';
    EntityCaption = 'Integration customer';
    EntitySetCaption = 'Integration customers';
    SourceTable = Customer;
    ODataKeyFields = SystemId;
    DelayedInsert = true;
    Extensible = false;

    layout
    {
        area(Content)
        {
            repeater(Records)
            {
                field(id; Rec.SystemId)
                {
                    Caption = 'Id';
                    Editable = false;
                }
                field(number; Rec."No.")
                {
                    Caption = 'Number';
                }
                field(displayName; Rec.Name)
                {
                    Caption = 'Display name';
                }
                field(email; Rec."E-Mail")
                {
                    Caption = 'Email';
                }
                field(lastModifiedDateTime; Rec.SystemModifiedAt)
                {
                    Caption = 'Last modified date time';
                    Editable = false;
                }
            }
        }
    }

    [ServiceEnabled]
    procedure SetIntegrationEmail(
        var ActionContext: WebServiceActionContext; email: Text[80])
    begin
        if email = '' then
            Error('Email must contain a value.');

        Rec.Validate("E-Mail", email);
        Rec.Modify(true);

        ActionContext.SetObjectType(ObjectType::Page);
        ActionContext.SetObjectId(Page::"Integration Customer API");
        ActionContext.AddEntityKey(Rec.FieldNo(SystemId), Rec.SystemId);
        ActionContext.SetResultCode(WebServiceActionResultCode::Updated);
    end;
}

The page publishes automatically with the extension. SystemId provides the entity key, and the bound action updates the entity in the request URL.

Implement the read-only API query

Create CustomerSnapshotAPI.Query.al.

query 71301 "Customer Snapshot API"
{
    QueryType = API;
    APIPublisher = 'training';
    APIGroup = 'integration';
    APIVersion = 'v1.0';
    EntityName = 'customerSnapshot';
    EntitySetName = 'customerSnapshots';
    Caption = 'Customer snapshots';
    DataAccessIntent = ReadOnly;

    elements
    {
        dataitem(Customer; Customer)
        {
            column(id; SystemId)
            {
                Caption = 'Id';
            }
            column(number; "No.")
            {
                Caption = 'Number';
            }
            column(displayName; Name)
            {
                Caption = 'Display name';
            }
            column(email; "E-Mail")
            {
                Caption = 'Email';
            }
            column(lastModifiedDateTime; SystemModifiedAt)
            {
                Caption = 'Last modified date time';
            }
        }
    }
}

This endpoint is read-only. The property declares that its GET workload can use a read-only connection when the environment supports one.

Implement the unbound action and secret store

Create IntegrationOperations.Codeunit.al.

codeunit 71302 "Integration Operations"
{
    procedure GetCustomerDisplayName(customerNumber: Code[20]): Text[100]
    var
        Customer: Record Customer;
    begin
        if customerNumber = '' then
            Error('Customer number must contain a value.');

        if not Customer.Get(customerNumber) then
            Error('Customer %1 does not exist.', customerNumber);

        exit(Customer.Name);
    end;
}

Create IntegrationSecretStore.Codeunit.al.

codeunit 71303 "Integration Secret Store"
{
    [NonDebuggable]
    procedure StoreCredential(CredentialText: Text)
    var
        Credential: SecretText;
    begin
        if CredentialText = '' then
            Error('Credential must contain a value.');

        Credential := CredentialText;
        if IsolatedStorage.Contains(CredentialKeyLbl, DataScope::Company)
        then
            IsolatedStorage.Delete(CredentialKeyLbl, DataScope::Company);

        if not IsolatedStorage.Set(
            CredentialKeyLbl, Credential, DataScope::Company)
        then
            Error('The credential could not be stored.');
    end;

    procedure GetCredential() Credential: SecretText
    begin
        if not IsolatedStorage.Get(
            CredentialKeyLbl, DataScope::Company, Credential)
        then
            Error('No integration credential is configured for this company.');
    end;

    procedure AddAuthorizationHeader(var Headers: HttpHeaders)
    var
        Credential: SecretText;
        AuthorizationValue: SecretText;
    begin
        Credential := GetCredential();
        AuthorizationValue := SecretStrSubstNo('Bearer %1', Credential);
        Headers.Add('Authorization', AuthorizationValue);
    end;

    procedure HasCredential(): Boolean
    begin
        exit(IsolatedStorage.Contains(
            CredentialKeyLbl, DataScope::Company));
    end;

    procedure DeleteCredential()
    begin
        if IsolatedStorage.Contains(CredentialKeyLbl, DataScope::Company)
        then
            IsolatedStorage.Delete(CredentialKeyLbl, DataScope::Company);
    end;

    var
        CredentialKeyLbl: Label 'IntegrationCredential', Locked = true;
}

Create IntegrationSecretSetup.Page.al.

page 71304 "Integration Secret Setup"
{
    PageType = Card;
    ApplicationArea = All;
    UsageCategory = Administration;
    Caption = 'Integration Secret Setup';

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

                field(CredentialInput; CredentialInput)
                {
                    ApplicationArea = All;
                    Caption = 'Credential';
                    ExtendedDatatype = Masked;
                }
                field(CredentialStored; CredentialStored)
                {
                    ApplicationArea = All;
                    Caption = 'Credential stored';
                    Editable = false;
                }
            }
        }
    }

    actions
    {
        area(Processing)
        {
            action(StoreCredential)
            {
                ApplicationArea = All;
                Caption = 'Store credential';
                Image = Save;

                trigger OnAction()
                begin
                    SecretStore.StoreCredential(CredentialInput);
                    Clear(CredentialInput);
                    UpdateStatus();
                end;
            }
            action(DeleteCredential)
            {
                ApplicationArea = All;
                Caption = 'Delete credential';
                Image = Delete;

                trigger OnAction()
                begin
                    SecretStore.DeleteCredential();
                    Clear(CredentialInput);
                    UpdateStatus();
                end;
            }
        }
    }

    trigger OnOpenPage()
    begin
        UpdateStatus();
    end;

    local procedure UpdateStatus()
    begin
        CredentialStored := SecretStore.HasCredential();
        CurrPage.Update(false);
    end;

    var
        SecretStore: Codeunit "Integration Secret Store";
        CredentialInput: Text[250];
        CredentialStored: Boolean;
}

The page reports only whether a value exists. It clears the short-lived text input after the nondebuggable setter converts and stores the value as SecretText.

Add explicit permissions

Create APIIntegration.PermissionSet.al.

permissionset 71305 "API Integration"
{
    Assignable = true;
    Caption = 'API integration';

    Permissions =
        tabledata Customer = RIMD,
        page "Integration Customer API" = X,
        query "Customer Snapshot API" = X,
        codeunit "Integration Operations" = X,
        codeunit "Integration Secret Store" = X,
        page "Integration Secret Setup" = X;
}

Publish the extension and assign the permission set to the account used for the exercise. In production, split setup permissions from runtime permissions when different roles manage credentials and call APIs.

Publish the unbound action

API pages and API queries are available after extension installation. The codeunit requires an OData publication entry.

  1. In Business Central, open Web Services.
  2. Create a line with Object Type set to Codeunit.
  3. Set Object ID to 71302.
  4. Set Service Name to IntegrationOperations.
  5. Turn on Published.
  6. Confirm that the OData V4 URL appears.

The action route combines IntegrationOperations and GetCustomerDisplayName with an underscore.

Create and run the API requests

Create integration-api.http and replace each placeholder with values for your sandbox. Keep the access token only in a local or secure environment variable if your request client supports one.

@baseUrl = https://api.businesscentral.dynamics.com/v2.0
@tenantId = <tenant-id>
@environmentName = <sandbox-name>
@companyId = <company-id>
@token = <oauth-access-token>
@customerId = <customer-system-id>

### Read the writable API entity
GET {{baseUrl}}/{{tenantId}}/{{environmentName}}/api/training/integration/v1.0/companies({{companyId}})/integrationCustomers?$select=id,number,displayName,email&$top=5
Authorization: Bearer {{token}}

### Read the snapshot query with read-only intent
GET {{baseUrl}}/{{tenantId}}/{{environmentName}}/api/training/integration/v1.0/companies({{companyId}})/customerSnapshots?$select=id,number,displayName,lastModifiedDateTime&$top=5
Authorization: Bearer {{token}}
Data-Access-Intent: ReadOnly

### Invoke the bound action
POST {{baseUrl}}/{{tenantId}}/{{environmentName}}/api/training/integration/v1.0/companies({{companyId}})/integrationCustomers({{customerId}})/Microsoft.NAV.SetIntegrationEmail
Authorization: Bearer {{token}}
Content-Type: application/json

{
  "email": "api.exercise@example.com"
}

### Invoke the bound action with invalid input
POST {{baseUrl}}/{{tenantId}}/{{environmentName}}/api/training/integration/v1.0/companies({{companyId}})/integrationCustomers({{customerId}})/Microsoft.NAV.SetIntegrationEmail
Authorization: Bearer {{token}}
Content-Type: application/json

{
  "email": ""
}

### Invoke the unbound action
POST {{baseUrl}}/{{tenantId}}/{{environmentName}}/ODataV4/IntegrationOperations_GetCustomerDisplayName?company={{companyId}}
Authorization: Bearer {{token}}
Content-Type: application/json

{
  "customerNumber": "10000"
}

Run the first request and copy one returned id value into customerId. Run the remaining requests. Confirm that the query is read-only, the valid bound action updates the selected entity, the invalid action returns the intended error, and the unbound action returns a scalar value.

Verify read intent and secret handling

Open Integration Secret Setup. Enter a nonproduction sample value, select Store credential, and confirm that Credential stored is selected. The page doesn't display the stored value. Select Delete credential and confirm that the status clears.

For the read-only query, record these facts:

  • The query declares DataAccessIntent = ReadOnly.
  • The request supplies Data-Access-Intent: ReadOnly.
  • The endpoint returns data but doesn't expose write operations.
  • A sandbox uses the primary database, so this run doesn't prove replica routing.
  • Production validation needs repeated performance or platform evidence from an environment where Read Scale-Out is available.

Submit the extension, successful and failed request evidence, and a short design record. Explain why the API page is writable, why the query is read-only, why each action is bound or unbound, why the credential uses company scope, and why the sandbox result isn't replica-routing evidence.