Study guide

17.2 Bound and Unbound OData Actions with [ServiceEnabled]

Microsoft Dynamics 365 Business Central Developer MB-820

Track your progress as you read

Finished sections get a check mark.

1 Chapter 1: Business Central Architecture & Platform Foundation

1.1 Business Central Architecture & Extensions Model 1.2 Customization Lifecycle: Cloud (SaaS) vs. On-Premises 1.3 Base Application, System Application & AppSource

2 Chapter 2: Development Environment & Configuration

2.1: Development Environment Setup: VS Code, AL: Go! Projects & Sandboxes 2.2: AL Configuration Files: app.json & launch.json Parameters 2.3: Multi-Root Workspaces & Project Dependencies

3 Chapter 3: Extension Lifecycle: Debugging, Deployment, Multilanguage & Maintenance

3.1 Debugging & Snapshot Debugging in Visual Studio Code 3.2 Extension Deployment & Schema Synchronization Modes 3.3 Multilanguage Development with XLIFF & Translation Files 3.4 Extension Maintenance, Deprecation & Breaking Changes

4 Chapter 4: Tables, Table Extensions & Data Modeling

4.1: Building Tables, Fields, Keys & Data Types 4.2: Table Extensions & Table Modifications 4.3: FlowFields, FlowFilters & Table Relations 4.4: Enums, Enum Extensions & Extensible Types

5 Chapter 5: Pages, Page Extensions & Role Centers

5.1: Page Types, Anatomy & Control Structure 5.2: Building Card, List & Document Pages 5.3: Page Extensions & Page Customizations 5.4: Role Centers, Headlines & Cue Data Modeling

6 Chapter 6: Reports & Document Generation

6.1 Report Architecture, DataItems & Dataset Design 6.2 Report Layouts: RDLC, Word, Excel & Multilanguage 6.3 Document Reports & Request Page Programming 6.4 Processing-Only Reports & Report Substitutions

7 Chapter 7: XMLports & Data Exchange

7.1 XMLport Architecture, Formats & Properties 7.2 XMLport Node Hierarchy, Triggers & Stream Manipulation

8 Chapter 8: Codeunits, Events, Triggers & Interfaces

8.1 Codeunit Types, Execution & SingleInstance Codeunits 8.2 Events, Publishers, Subscribers & Event Isolation 8.3 Interfaces, Polymorphism & Dynamic Codeunit Invocation 8.4 Installation & Upgrade Codeunits, Data Transfer & Archive

9 Chapter 9: Entitlements, Permissions & Queries

9.1 Permission Sets & Permission Set Extensions 9.2 Inherent Permissions, Inherent Entitlements & Security Scoping 9.3 Query Objects: Joins, Aggregation & Query as Report Data Source

10 Chapter 10: UI Customization, User Assistance & Onboarding

10.1 Profile Objects & Custom Page Views in AL 10.2 User Assistance: ToolTips, Teaching Tips & In-App Tours 10.3 Assisted Setup, Guided Experience & Onboarding Checklists

11 Chapter 11: Business Central Design Patterns & Data Process Model

11.1 Functional Table Types: Master Data, Supplemental & Setup Patterns 11.2 Document Standards: Header, Line, History & Journal Architectures 11.3 Data Process Model & Posting Routine Architecture

12 Chapter 12: AL Language Fundamentals, Data Types & Variables

12.1 AL Syntax, Variable Scope, Primitive & Complex Data Types 12.2 Expressions, Control Flow Statements & Built-in Functions 12.3 Access Modifiers (Public, Internal, Local) & Code Scoping

13 Chapter 13: Data Manipulation, Streams & Error Handling

13.1 Record Operations: Get, FindSet, ModifyAll & Filter Functions 13.2 Streams, File Management & TempBlob 13.3 Error Handling: ErrorInfo, TryFunctions & Collectible Errors

14 Chapter 14: Testing, Test Toolkit & Automation

14.1 Testing Architecture & the Test Toolkit 14.2 Authoring Test Codeunits & UI Handler Functions

15 Chapter 15: Telemetry, Performance Optimization & Analyzers

15.1 Telemetry Configuration & Azure Application Insights 15.2 Custom Telemetry Signals with Session.LogMessage & KQL 15.3 Performance Profiler, SetLoadFields & Query Optimization 15.4 AL Analyzers: CodeCop, AppSourceCop, UICop & PTECop

16 Chapter 16: REST Web Services & JSON in AL

16.1 HttpClient, HttpRequestMessage & REST API Consumption 16.2 JSON Processing: JsonObject, JsonArray, JsonValue & JsonToken

17 Chapter 17: API Pages, OData, Read Scale-Out & OAuth

17.1 API Pages (PageType=API), OData Web Services & REST Endpoints 17.2 Bound and Unbound OData Actions with [ServiceEnabled] 17.3 Read Scale-Out Architecture & DataAccessIntent Configuration 17.4 Microsoft Entra ID App Registrations & OAuth 2.0 Integration

17.2 Bound and Unbound OData Actions with [ServiceEnabled]

Key Takeaways Explain This Topic AI

OData Actions in Business Central allow external applications to invoke business logic, state transitions, and custom processing routines over REST endpoints using HTTP POST requests.

In AL, an action procedure exposed to REST/OData must be decorated with the [ServiceEnabled] attribute and declared within an API page or web service-exposed codeunit.

Bound actions operate on a specific existing entity instance (the current Rec), addressed via the entity's primary key URL (e.g., /customCustomers({id})/Microsoft.NAV.blockCustomer).

Unbound actions are static operations not tied to an individual record instance, invoked at the entity set root (e.g., /customCustomers/Microsoft.NAV.recalculateAllDiscounts) or on a web service codeunit.

The WebServiceActionContext data type manages HTTP response status and location headers using SetResultCode(WebServiceActionResultCode::Created/Updated/Deleted/None), SetObjectType(ObjectType::Page), and SetObjectId(Page::"Custom Customer API").

Last updated: August 2026

17.2 Bound and Unbound OData Actions with [ServiceEnabled]

While standard RESTful operations on API pages handle basic CRUD activities (Create via POST , Read via GET , Update via PATCH , Delete via DELETE ), enterprise integrations frequently require invoking complex server-side business routines—such as releasing a sales document, posting an invoice, recalculating customer credit limits, or canceling an order. In Business Central, developers implement these remote procedure calls (RPC) using OData Actions decorated with the [ServiceEnabled] attribute.

1. OData Actions Architecture & Execution Model

An OData Action is an operation exposed through the OData v4 metadata schema ( $metadata ) that can execute state-changing business logic on the Business Central Server tier. +-------------------------------------------------------------------------+

  • | EXTERNAL REST CLIENT |
  • | (HTTP POST /Microsoft.NAV.{actionName}) |
  • +-----------------------------------┬-------------------------------------+
  • │ (JSON Parameter Payload)
  • ▼
  • +-------------------------------------------------------------------------+
  • | BUSINESS CENTRAL OData ACTION DISPATCHER |
  • | |
  • | 1. Locate Target Object (API Page / Codeunit Web Service) |
  • | 2. Bind Entity Context (Fetch Rec for Bound; Skip for Unbound) |
  • | 3. Deserialize Action Parameters from Request Body |
  • | 4. Initialize WebServiceActionContext Reference |
  • +-----------------------------------┬-------------------------------------+
  • │ (Invoke AL Procedure)
  • ▼
  • +-------------------------------------------------------------------------+
  • | AL BUSINESS LOGIC & TRANSACTION |
  • | |
  • | [ServiceEnabled] |
  • | procedure ProcessAction(Params...; var ActionContext: ActionContext) |
  • | - Execute Business Logic (e.g., Post, Release, Validate) |
  • | - Configure ActionContext (SetResultCode, SetObjectId, AddKey) |
  • +-----------------------------------┬-------------------------------------+
  • │ (Construct HTTP Response)
  • ▼
  • +-------------------------------------------------------------------------+
  • | HTTP RESPONSE STATUS & HEADERS |
  • | - HTTP 200 OK (Updated / Returned Object) |
  • | - HTTP 201 Created (Created Resource + Location Header) |
  • | - HTTP 204 No Content (None / Completed without Body) |
  • | - HTTP 400 / 500 (AL Error Dialog converted to JSON Error) |
  • +-------------------------------------------------------------------------+
  • Core Rules Governing OData Actions

HTTP Method: All OData Actions must be invoked using the POST HTTP verb. GET , PUT , or PATCH requests to an action endpoint will return 405 Method Not Allowed .

Attribute Decoration: The procedure in AL must be decorated with [ServiceEnabled] .

Namespace Prefix: In the OData v4 metadata and endpoint URL, Business Central actions are always prefixed with the runtime namespace: Microsoft.NAV.<ProcedureName> (case-sensitive or matching exact AL procedure casing).

Transaction Boundary: The entire action procedure executes within a single database transaction. If an unhandled error occurs or an Error('...') statement is encountered, all database changes made during the action are automatically rolled back, and an HTTP 400 Bad Request or 500 Internal Server Error response is returned.

Loading diagram... Bound vs. Unbound OData Action Invocation & Endpoint Resolution

2. Implementing Bound OData Actions

A Bound Action is explicitly tied to a specific entity record instance. When the external client calls a bound action, the Business Central server automatically resolves the entity key in the URL and loads that specific record into the page's Rec buffer before executing the procedure.

  • AL Implementation of a Bound Action on an API Page page 50130 "Custom Customer API"
  • {
  • PageType = API;
  • Caption = 'customCustomer';
  • APIPublisher = 'custom';
  • APIGroup = 'integrations';
  • APIVersion = 'v2.0';
  • EntityName = 'customCustomer';
  • EntitySetName = 'customCustomers';
  • SourceTable = Customer;
  • DelayedInsert = true;
  • ODataKeyFields = SystemId;
  • layout
  • {
  • area(Content)
  • {
  • repeater(Group)
  • {
  • field(id; Rec.SystemId) { }
  • field(number; Rec."No.") { }
  • field(displayName; Rec.Name) { }
  • field(blocked; Rec.Blocked) { }
  • }
  • }
  • }
  • [ServiceEnabled]
  • procedure BlockCustomer(ReasonCode: Code[10]; Comments: Text[100]; var ActionContext: WebServiceActionContext)
  • var
  • CustomerPostingMsg: Label 'Customer %1 was blocked via API. Reason: %2, Comments: %3', Locked = true;
  • begin
  • // The runtime has already loaded Rec matching the URL SystemId
  • Rec.TestField(Blocked, Rec.Blocked::" ");
  • Rec.Validate(Blocked, Rec.Blocked::All);
  • Rec.Modify(true);
  • // Configure the HTTP Response Context
  • ActionContext.SetResultCode(WebServiceActionResultCode::Updated);
  • end;
  • }
  • External HTTP Invocation (Bound Action)

To invoke this bound action, the client sends an HTTP POST to the specific customer entity URI, qualifying the action name with Microsoft.NAV. : POST https://api.businesscentral.dynamics.com/v2.0/{tenant}/{env}/api/custom/integrations/v2.0/companies(12345678-1234-1234-1234-123456789abc)/customCustomers(d4f5a6b7-8901-2345-6789-abcdef012345)/Microsoft.NAV.blockCustomer

Content-Type: application/json

  • {
  • "ReasonCode": "OVERDUE",
  • "Comments": "Account placed on hold due to unpaid invoices exceeding 90 days."
  • }
  • HTTP Response: HTTP/1.1 200 OK
  • Content-Type: application/json; odata.metadata=minimal
  • {
  • "@odata.context": "https://api.businesscentral.dynamics.com/v2.0/.../$metadata#customCustomers/$entity",
  • "id": "d4f5a6b7-8901-2345-6789-abcdef012345",
  • "number": "C00010",
  • "displayName": "Contoso Ltd.",
  • "blocked": "All"
  • }

3. Implementing Unbound OData Actions

An Unbound Action is a global or collection-level operation not tied to a single existing record instance. Unbound actions can be declared on API pages (invoked at the entity set root) or inside Codeunits published as OData Web Services.

  • AL Implementation of an Unbound Action on an API Page page 50130 "Custom Customer API"
  • {

// ... (properties and layout) ...

  • [ServiceEnabled]
  • procedure RecalculateAllDiscounts(CustomerCategory: Code[20]; var ActionContext: WebServiceActionContext)
  • var
  • Cust: Record Customer;
  • DiscountMgt: Codeunit "Cust-Order Discount";
  • begin
  • Cust.SetRange("Customer Disc. Group", CustomerCategory);
  • if Cust.FindSet(true) then
  • repeat
  • DiscountMgt.UpdateCustomerDiscounts(Cust);
  • until Cust.Next() = 0;
  • ActionContext.SetResultCode(WebServiceActionResultCode::None);
  • end;
  • }
  • External HTTP Invocation (Unbound Action)

Notice that the URI addresses the entity set root ( customCustomers ) rather than an individual entity GUID: POST https://api.businesscentral.dynamics.com/v2.0/{tenant}/{env}/api/custom/integrations/v2.0/companies(12345678-1234-1234-1234-123456789abc)/customCustomers/Microsoft.NAV.recalculateAllDiscounts

Content-Type: application/json

  • {
  • "CustomerCategory": "RETAIL"
  • }
  • HTTP Response: HTTP/1.1 204 No Content
  • Unbound Actions on Web Service Codeunits

Developers can also publish a Codeunit as an OData Web Service. Every public procedure inside that codeunit becomes an unbound action callable over OData v4: codeunit 50140 "Integration Service"

  • {
  • procedure ProcessPendingShipments(WarehouseLocation: Code[10]): Integer
  • var
  • WarehouseMgt: Codeunit "Warehouse Management";
  • begin
  • exit(WarehouseMgt.ShipAllPendingOrders(WarehouseLocation));
  • end;
  • }

4. Managing HTTP Response Context with WebServiceActionContext

The WebServiceActionContext data type gives AL developers precise control over the HTTP status codes, headers, and entity keys returned to the calling client.

Key Methods on WebServiceActionContext

Method Purpose & Usage

SetResultCode(WebServiceActionResultCode) Sets the HTTP response status. Takes an enum value: Created (201), Updated (200), Deleted (204), or None (204).

SetObjectType(ObjectType) Specifies the metadata object type of the resulting entity (e.g., ObjectType::Page ). Required when Created or Updated is used.

SetObjectId(Integer) Specifies the object ID of the API Page displaying the entity (e.g., Page::"Custom Customer API" ).

AddEntityKey(FieldNo, Value) Adds key-value pairs (e.g., Rec.FieldNo(SystemId), Rec.SystemId ) to generate the OData @odata.id and Location URI headers.

Complete Example: Action Creating a New Resource (HTTP 201 Created)

When an action creates a new entity (such as posting an order and generating a Posted Sales Invoice), developers configure WebServiceActionContext so the client receives an HTTP 201 status and the URI of the newly created invoice: [ServiceEnabled]

  • procedure CreateContractInvoice(ContractNo: Code[20]; var ActionContext: WebServiceActionContext)
  • var
  • SalesHeader: Record "Sales Header";
  • ContractMgt: Codeunit "Contract Management";
  • begin
  • // Execute business routine that creates and inserts a new Sales Header
  • ContractMgt.CreateInvoiceForContract(ContractNo, SalesHeader);
  • // Build response context pointing to the newly created Sales Header API
  • ActionContext.SetResultCode(WebServiceActionResultCode::Created);
  • ActionContext.SetObjectType(ObjectType::Page);
  • ActionContext.SetObjectId(Page::"Custom Sales Invoice API");
  • ActionContext.AddEntityKey(SalesHeader.FieldNo(SystemId), SalesHeader.SystemId);
  • end;
  • WebServiceActionResultCode Status Code Mapping

WebServiceActionResultCode::None -> 204 No Content (Request succeeded; no body returned).

WebServiceActionResultCode::Updated -> 200 OK (Returns updated entity JSON in response body).

WebServiceActionResultCode::Created -> 201 Created (Returns newly created entity JSON + Location response header).

WebServiceActionResultCode::Deleted -> 204 No Content (Resource was successfully deleted).