Creating OData Bound and Unbound Actions

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 10 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Mastering Business Central: Implementing OData Bound and Unbound Actions

Introduction: The Power of Custom API Logic

In the world of enterprise resource planning (ERP), Dynamics 365 Business Central serves as the central nervous system for many organizations. While the platform provides a vast array of standard API endpoints for reading and writing data, real-world business requirements often demand more than simple CRUD (Create, Read, Update, Delete) operations. This is where OData (Open Data Protocol) actions come into play. By implementing custom actions, you extend the capabilities of your API, allowing external systems to trigger complex business logic, perform calculations, or initiate workflows directly within Business Central.

Understanding the distinction between bound and unbound actions is a fundamental skill for any developer working with the AL (Application Language) environment. Bound actions are tied to specific records, making them perfect for operations like "Post Invoice" or "Calculate Discount" on a specific sales order. Unbound actions, conversely, are global in nature; they act on the service level rather than a specific record, which is ideal for tasks like "Clear Cache," "Generate Monthly Report," or "Sync External Data." Mastering these tools allows you to build sophisticated, high-performance integrations that go far beyond standard data synchronization.


Not read yet

Understanding OData Actions in Business Central

OData actions are effectively custom functions exposed through your API that can be invoked via HTTP POST requests. Unlike standard API operations that manipulate data fields directly, actions allow you to execute server-side AL code. This is crucial because it ensures that all business rules, validation logic, and posting routines defined in the Business Central codebase are respected, regardless of whether the request comes from a Power Automate flow, a custom web application, or a mobile front-end.

To implement these, you define them within an api object or a page object in AL. The syntax requires specific attributes—specifically [ServiceEnabled]—which signals to the platform that the function should be exposed via OData. Without this attribute, the function remains private to the internal environment. This design pattern enforces a strict boundary between internal utility functions and externally accessible interface methods.

Callout: Bound vs. Unbound - The Conceptual Difference The core difference lies in the context of the execution. A bound action operates on a specific instance of a record (e.g., "Archive this specific Customer"), effectively acting as a method on an object. An unbound action operates on the service level (e.g., "Refresh all exchange rates"), acting more like a static global function. Choosing the right type depends entirely on whether your operation requires a primary key identifier to function.


Not read yet

Implementing Bound Actions

Bound actions are the most common type of custom API logic. When you define a bound action, the API endpoint automatically includes the primary key of the record in the URL. For example, if you have a bound action called processOrder on a Sales Order API, the endpoint will look like .../SalesOrders(id='...')/Microsoft.NAV.processOrder.

Step-by-Step: Creating a Bound Action

To create a bound action, you must define it within a page object of type API. The function must be marked with the [ServiceEnabled] attribute.

  1. Define the Page: Ensure your page type is set to API.
  2. Declare the Function: Inside the page, create a procedure.
  3. Apply Attributes: Add [ServiceEnabled] above the procedure.
  4. Accessing Data: Since it is bound, you can directly access the fields of the current record (Rec).

Example: Calculating a Custom Discount

Let's assume we want to create an action that applies a special discount to a specific Sales Order based on a business rule.

page 50100 "CustomSalesOrderAPI"
{
    PageType = API;
    APIPublisher = 'myCompany';
    APIGroup = 'sales';
    APIVersion = 'v1.0';
    EntityName = 'salesOrder';
    EntitySetName = 'salesOrders';
    SourceTable = "Sales Header";

    layout
    {
        area(Content)
        {
            repeater(Group)
            {
                field(id; SystemId) { }
                field(no; "No.") { }
                field(status; Status) { }
            }
        }
    }

    [ServiceEnabled]
    procedure applySpecialDiscount(var ActionContext: WebServiceActionContext)
    var
        SalesLine: Record "Sales Line";
    begin
        // The 'Rec' variable refers to the current Sales Header record
        if Rec.Status = Rec.Status::Released then
            error('Cannot apply discount to a released order.');

        SalesLine.SetRange("Document Type", Rec."Document Type");
        SalesLine.SetRange("Document No.", Rec."No.");
        if SalesLine.FindSet() then begin
            repeat
                SalesLine."Line Discount %" := 10;
                SalesLine.Modify();
            until SalesLine.Next() = 0;
        end;
    end;
}

In the example above, the ActionContext parameter is optional but recommended if you need to provide a response back to the client or redirect the user after the action completes. The [ServiceEnabled] attribute ensures the procedure is visible to the OData metadata.


Not read yet

Implementing Unbound Actions

Unbound actions are defined at the page level but do not require a specific record context. They are typically used for administrative or global tasks. Because they are not bound to a record, they do not appear in the context of a specific entity URL. Instead, they are accessed via the service root or a specific page endpoint that defines them globally.

Step-by-Step: Creating an Unbound Action

  1. Define the Page: You can add an unbound action to any API page.
  2. Use Bound vs. Unbound: To make it unbound, we usually define it in a way that it doesn't require a record lookup, or we place it in a specialized singleton page.
  3. Parameters: You can pass parameters to unbound actions, which are sent via the JSON body of the POST request.

Example: Global Exchange Rate Refresh

page 50101 "GlobalIntegrationAPI"
{
    PageType = API;
    APIPublisher = 'myCompany';
    APIGroup = 'system';
    APIVersion = 'v1.0';
    EntityName = 'integrationTask';
    EntitySetName = 'integrationTasks';
    SourceTable = "Currency"; // Even if we don't use the table, we need a source

    [ServiceEnabled]
    procedure RefreshExchangeRates(var ActionContext: WebServiceActionContext; CurrencyCode: Code[10])
    var
        Currency: Record Currency;
    begin
        if Currency.Get(CurrencyCode) then begin
            // Logic to fetch new rates from an external provider
            Currency."Last Date Modified" := Today;
            Currency.Modify();
        end;
    end;
}

Note: When using parameters in OData actions, ensure the parameter names in your AL procedure match the names expected in the JSON payload exactly. OData is case-sensitive, and mismatches will result in 400 Bad Request errors.


Not read yet

Comparing Bound and Unbound Actions

To make the right architectural choice, consider the following comparison:

Feature Bound Action Unbound Action
Context Operates on a specific record Operates on the service/global level
URL Structure .../Entity(id)/ActionName .../ActionName (or via service root)
Primary Usage Modifying specific document states System-wide utility or triggers
Access Requires a valid ID Does not require an ID
Execution Uses Rec directly Uses passed parameters

Best Practices for API Development

When building APIs in Business Central, you are exposing the core of your business logic. Security, performance, and maintainability are paramount.

1. Robust Error Handling

Always wrap your logic in try-catch blocks where appropriate, or use clear validation checks. If an action fails, return meaningful error messages. Using Error() in AL will roll back the transaction and return a 500 status code to the client, which is the desired behavior for failed business logic.

2. Parameter Validation

Never trust the input coming from an external system. Always validate parameters in your [ServiceEnabled] procedure. If a user passes a negative amount or a non-existent code, catch this early and provide a clear error before attempting to modify records.

3. Minimize Database Impact

API actions are often called in high-frequency loops by external integration tools. Ensure your logic is optimized. Avoid FindSet() loops where SetRange() or ModifyAll() can accomplish the same task. The more efficient your code, the better the overall responsiveness of your Business Central instance.

4. Versioning Your API

Always use the APIVersion property. As your business needs evolve, you may need to change the logic of an action. By keeping versioned endpoints, you ensure that older integrations do not break when you deploy updates to your AL code.

Tip: Using WebServiceActionContext The WebServiceActionContext object allows you to control the response headers and the location of the result. For instance, you can use ActionContext.AddEntityKey() to return the ID of a newly created record after an action runs, allowing the client to immediately identify the result of the operation.


Not read yet

Common Pitfalls and How to Avoid Them

Pitfall 1: Forgetting the [ServiceEnabled] Attribute

This is the most common mistake. Developers often write the procedure but forget the attribute. If the action is missing from the $metadata document of your API, verify this attribute is present and that the page is published correctly.

Pitfall 2: Overloading Actions

Avoid putting massive amounts of code inside an action. If your action performs ten different tasks, break it down into smaller, private helper procedures within the same AL object. This improves readability and makes testing much easier.

Pitfall 3: Ignoring Transactional Integrity

Business Central APIs are transactional. If your action modifies three tables and the third one fails, the entire request will roll back. This is actually a feature, not a bug, but you must be aware of it. Ensure that your logic is designed to be atomic—either all changes succeed, or none of them do.

Pitfall 4: Hardcoding Values

Avoid hardcoding IDs or specific configuration values within your action procedures. Use Table records to store configuration settings or use Setup tables. Hardcoded values make your API fragile and difficult to move between environments (e.g., from Sandbox to Production).


Not read yet

Practical Example: Implementing a Batch Processing Action

Sometimes, you need to perform an action on multiple records at once. While standard OData actions are usually single-record or service-level, you can create a "Batch" unbound action that accepts an array of identifiers.

[ServiceEnabled]
procedure ProcessMultipleOrders(var ActionContext: WebServiceActionContext; OrderIds: List of [Guid])
var
    SalesHeader: Record "Sales Header";
    OrderId: Guid;
begin
    foreach OrderId in OrderIds do begin
        if SalesHeader.GetBySystemId(OrderId) then begin
            // Perform logic
            SalesHeader.Status := SalesHeader.Status::Released;
            SalesHeader.Modify();
        end;
    end;
end;

This approach allows you to reduce the number of HTTP calls significantly. Instead of calling a bound action 50 times for 50 orders, you call one unbound action once, passing a list of IDs. This is a common industry pattern for optimizing performance in high-volume integrations.


Not read yet

Security Considerations

Exposing actions via OData effectively opens a door into your system. You must ensure that the user account (or service principal) making the call has the appropriate permissions.

  1. Permission Sets: Ensure that the API user has the necessary permissions to execute the code within the action. If the action modifies a Sales Header, the user needs "Modify" permissions on that table.
  2. Input Sanitization: While AL is generally safe from SQL injection, you should still ensure that any strings passed as parameters are validated against expected formats (e.g., using Evaluate or regex patterns).
  3. Audit Logging: If your action performs critical financial or operational updates, consider writing a custom log entry to a dedicated "Integration Log" table. This provides an audit trail of who called the action and when, which is vital for compliance.

Testing Your Actions

Testing is the final, and perhaps most important, step. You cannot rely on manual testing alone for API actions.

  • Postman/Insomnia: Use tools like Postman to manually trigger your POST requests. This allows you to inspect the JSON body, the headers, and the response code.
  • Automated Tests: Create AL test codeunits. You can simulate an API call by invoking the procedure directly in your test code and asserting that the resulting table states match your expectations.
  • OData Metadata Check: Always review the $metadata endpoint of your API. This is the source of truth for what your API exposes. If it isn't in the metadata, it doesn't exist for the outside world.

Not read yet

Advanced OData Concepts: Returning Data

Often, an action should not just "do something" but also return a result. While WebServiceActionContext handles the metadata, you can also return values from your procedures.

[ServiceEnabled]
procedure GetOrderSummary(var ActionContext: WebServiceActionContext): Text
var
    Summary: Text;
begin
    // Logic to build a summary string
    Summary := 'Order processed successfully: ' + Rec."No.";
    exit(Summary);
end;

When you return a value, the OData response will contain the result in the value field of the JSON response. This is highly useful for providing feedback to the calling application, such as returning a generated invoice number or a confirmation token.


Integration with Power Automate

One of the primary consumers of Business Central APIs is Power Automate. When you create an action, it becomes available in the "Call Business Central Action" connector.

  1. Discovery: Once your API is published, open Power Automate.
  2. Action Selection: Select the "Business Central" connector and the "Call an action" trigger.
  3. Binding: If it is a bound action, you will be prompted to select the record ID. If it is unbound, you will see it listed under the service actions.
  4. Data Mapping: Power Automate will automatically parse the parameters you defined in your AL code, allowing you to pass dynamic content from other connectors (like SharePoint or Outlook) directly into your Business Central logic.

Not read yet

Troubleshooting Checklist

If your API action is not working as expected, run through this checklist before diving into deep debugging:

  • Is the service published? Check the "Web Services" page in Business Central to ensure your API page is listed.
  • Is the attribute correct? Ensure [ServiceEnabled] is present and spelled correctly.
  • Is the JSON valid? If you are passing parameters, ensure the JSON body is well-formed. A missing bracket or comma will cause a silent failure or a 400 error.
  • Are permissions sufficient? Log in as the API user and attempt a standard read operation to verify the user has access to the underlying table.
  • Check the Event Viewer: If you are on an on-premise installation, check the Windows Event Viewer for Business Central server logs. For cloud instances, check the "Telemetry" logs in Application Insights.

Key Takeaways

  1. Context is King: Always determine if your logic belongs to a specific record (Bound) or the system as a whole (Unbound) before writing code.
  2. Attribute Requirements: The [ServiceEnabled] attribute is the mandatory gateway for exposing any procedure to the OData API.
  3. Efficiency Matters: Design your actions to handle batch operations where possible to reduce network overhead and improve integration performance.
  4. Security First: Treat every API action as a potential entry point for unauthorized or malformed data; validate all inputs and ensure proper permissions are set.
  5. Standardization: Use consistent naming conventions for your API actions to make them intuitive for other developers and integration tools.
  6. Transactional Integrity: Remember that Business Central handles API actions as atomic transactions; design your logic to handle rollbacks gracefully.
  7. Documentation: Keep your API documentation updated, especially when adding new actions or changing parameter structures, to ensure external systems remain compatible.

By following these principles, you will be able to build powerful, reliable, and secure integrations that extend the value of your Dynamics 365 Business Central implementation. The ability to bridge the gap between external requirements and internal business logic is what separates a standard implementation from a high-performance enterprise ecosystem. Keep your code clean, your logic modular, and your API documentation clear, and you will provide immense value to your organization's digital infrastructure.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.