Creating and Working with APIs

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 11 read · keep scrolling

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

Lesson: Creating and Working with APIs in Business Central

Introduction: Why APIs are the Backbone of Modern Business Central Integration

In the modern enterprise landscape, no software application operates in a vacuum. Your Enterprise Resource Planning (ERP) system, such as Microsoft Dynamics 365 Business Central, acts as the central nervous system of your business data. However, to truly maximize the value of that data, it must flow freely between your ERP, your e-commerce platform, your CRM, your reporting tools, and your custom mobile applications. This is where Application Programming Interfaces (APIs) become indispensable.

An API serves as a bridge, allowing different software systems to communicate, exchange data, and trigger processes without requiring manual intervention or insecure workarounds. When you integrate Business Central with external systems using APIs, you eliminate data silos, reduce the risk of human error in manual data entry, and enable real-time visibility into your business operations. Understanding how to create, secure, and manage these APIs is a critical skill for any developer or consultant working within the Business Central ecosystem.

In this lesson, we will explore the technical architecture of Business Central APIs, how to build custom API pages using AL (Application Language), how to handle authentication, and how to follow industry-standard practices to ensure your integrations are stable, performant, and secure.


Not read yet

Understanding the API Architecture in Business Central

Business Central provides two primary ways to interact with data via web services: OData (Open Data Protocol) and the newer, more specialized API framework. While OData web services are still supported for backward compatibility, the modern API framework built on top of OData v4 is the standard for new development.

The API framework in Business Central is designed for developers who need to expose data in a way that is consumable by modern web and mobile applications. It uses REST (Representational State Transfer) principles, making it highly compatible with standard HTTP methods like GET, POST, PATCH, and DELETE.

Key Characteristics of Business Central APIs:

  • Resource-Oriented: APIs are built around "resources," which are essentially representations of the data entities you want to expose, such as Customers, Sales Orders, or Items.
  • Versioned: Business Central APIs support versioning, allowing you to iterate on your API design without breaking existing integrations.
  • Standardized: They rely on standard JSON (JavaScript Object Notation) for data exchange, which is the most widely supported format for web-based data transfer.
  • Context-Aware: APIs are aware of the tenant and company context, ensuring that you only access the data you are authorized to see within a specific environment.

Callout: OData Web Services vs. Custom APIs While OData web services created from standard pages are easy to set up, they are often difficult to maintain because they are tightly coupled to the UI. Custom APIs, on the other hand, are designed specifically for machine-to-machine communication. They allow you to define custom fields, enforce strict data validation, and create meaningful relationships between entities that don't necessarily reflect the user interface structure.


Not read yet

Building Your First Custom API

To create a custom API in Business Central, you must use the AL development environment. Unlike traditional pages, API pages have specific properties that identify them as service endpoints.

Step-by-Step: Creating an API Page

  1. Define the Object: Create a new file in your AL project with the extension .al.
  2. Use the page object: Use the api type for the page.
  3. Set Essential Properties: You must define the APIPublisher, APIGroup, APIVersion, EntityName, and EntitySetName.
  4. Define the Layout: Just like a standard page, you define the fields you want to expose in the layout section.

Code Example: A Simple API Page for Custom Records

page 50100 "MyCustomEntityAPI"
{
    PageType = API;
    Caption = 'My Custom Entity';
    APIPublisher = 'myCompany';
    APIGroup = 'customIntegration';
    APIVersion = 'v1.0';
    EntityName = 'myCustomEntity';
    EntitySetName = 'myCustomEntities';
    SourceTable = "MyCustomTable";
    DelayedInsert = true;
    ODataKeyFields = SystemId;

    layout
    {
        area(Content)
        {
            repeater(GroupName)
            {
                field(id; SystemId)
                {
                    Caption = 'ID';
                    Editable = false;
                }
                field(code; Code)
                {
                    Caption = 'Code';
                }
                field(description; Description)
                {
                    Caption = 'Description';
                }
            }
        }
    }
}

Explaining the Properties

  • APIPublisher: This acts as a namespace to prevent conflicts with other extensions. Use a unique value related to your organization.
  • APIGroup: This allows you to categorize your APIs. For example, you might have a group for 'sales' and another for 'inventory'.
  • APIVersion: This helps you manage updates. When you make a breaking change, you can increment the version (e.g., from v1.0 to v2.0).
  • EntityName: The singular name of the resource.
  • EntitySetName: The plural name of the resource, which is what you will use in your URL endpoint.
  • ODataKeyFields: Always use SystemId as your key field. It is a unique, immutable identifier that is perfect for API interactions.

Not read yet

Working with API Endpoints

Once you have published your extension to Business Central, your API becomes available at a specific URL. The URL structure follows a predictable pattern:

https://api.businesscentral.dynamics.com/v2.0/{tenantId}/{environment}/api/{publisher}/{group}/{version}/{entitySetName}

HTTP Methods and Their Roles

Understanding how to use HTTP methods correctly is vital for building a robust integration:

  • GET: Retrieve data. You can use query parameters to filter, sort, or limit the number of records returned.
  • POST: Create new records. The request body must contain the data for the new entity in JSON format.
  • PATCH: Update existing records. You only need to include the fields you wish to change.
  • DELETE: Remove a record from the database.

Note: Always use PATCH rather than PUT for updates. PUT implies a complete replacement of the resource, which often leads to unintended data loss if you omit fields, whereas PATCH allows for granular field-level updates.


Not read yet

Authentication and Security

Security is the most critical aspect of any API implementation. Business Central uses OAuth 2.0 as the standard for authenticating API requests. You should never use basic authentication (username and password) for integrations, as it is insecure and deprecated in modern cloud environments.

The OAuth 2.0 Flow

  1. Register an App: Register your application in the Microsoft Entra ID (formerly Azure AD) portal.
  2. Define Permissions: Grant your application the necessary API permissions (e.g., Financials.ReadWrite.All).
  3. Obtain a Token: Your application requests an access token from the Microsoft identity platform.
  4. Send the Request: Include the access token in the Authorization header of your HTTP request (Bearer {token}).

Warning: Never hardcode your Client ID, Client Secret, or any credentials in your source code. Use Azure Key Vault or a similar secure environment variable management system to store sensitive configuration data.


Not read yet

Best Practices for API Design and Performance

Building an API is not just about making it work; it is about making it efficient and easy for other developers to use. Follow these industry standards to ensure your APIs are "production-ready."

1. Optimize Data Retrieval

Only expose the fields that are actually needed by the consuming application. Exposing large, unused fields can increase the payload size and degrade performance, especially when fetching lists of records.

2. Implement Proper Filtering

Always allow filtering on the server side using OData query parameters like $filter, $select, and $top. This prevents the client from downloading entire tables when they only need a subset of records.

3. Handle Errors Gracefully

Your API should return meaningful HTTP status codes.

  • 200 OK: Success.
  • 201 Created: Successfully created a new resource.
  • 400 Bad Request: The client sent invalid data.
  • 401 Unauthorized: Authentication failed.
  • 404 Not Found: The requested resource does not exist.
  • 500 Internal Server Error: An unexpected error occurred on the server.

4. Use Proper Data Types

Ensure that your API fields map correctly to the data types expected by the consuming system. For example, dates should always be formatted in ISO 8601 format to avoid ambiguity across different regional settings.

5. Document Your APIs

Even if your API seems simple, provide documentation. Include examples of JSON requests and responses, explain the required fields, and describe the purpose of each endpoint. A tool like Postman is excellent for testing and documenting your API endpoints.


Not read yet

Common Pitfalls and How to Avoid Them

Even experienced developers encounter issues when working with Business Central APIs. Here are the most common mistakes and strategies to avoid them.

Pitfall 1: Ignoring API Limits

Business Central imposes limits on the number of requests and the amount of data transferred to ensure system stability. If you are syncing large volumes of data, perform your operations in batches rather than individual requests.

Pitfall 2: Over-fetching Data

Fetching a list of 10,000 customers when you only need the top 50 is a common performance killer. Always use the $top and $skip parameters to implement pagination in your integration logic.

Pitfall 3: Failing to Handle Concurrency

In a multi-user environment, two systems might try to update the same record simultaneously. Use the ETag header to handle optimistic concurrency. If the record has changed since the client last read it, the API will return a 412 Precondition Failed error, allowing the client to handle the conflict appropriately.

Pitfall 4: Neglecting Business Logic

APIs bypass the standard user interface, which means you must ensure your API code triggers the same validation logic as the UI. If you are inserting a Sales Order, make sure your code calls the appropriate table triggers or codeunits to calculate taxes, update inventory, and validate dimensions.

Callout: The Importance of Table Triggers When working with APIs, keep in mind that the OnInsert, OnModify, and OnDelete triggers on your table will execute. This is a good thing! It ensures that your business rules are enforced regardless of whether the record was created by a human in the UI or by an automated API call.


Not read yet

Comparison: OData vs. API Pages

Feature OData Web Services Custom API Pages
Ease of Setup High (Expose existing pages) Medium (Requires new AL code)
Performance Moderate High (Optimized for APIs)
Customization Low High (Full control over structure)
Versioning No built-in support Versioning supported
Integration Type Legacy/General Modern/Machine-to-Machine

Advanced Scenarios: Complex Integrations

Sometimes, a single entity is not enough. You might need to perform an action, such as "Post" a Sales Order, which involves executing logic rather than just updating a field.

Handling Actions with Bound Actions

You can add custom actions to your API pages. These actions allow the client to trigger specific functions within Business Central.

page 50101 "MySalesOrderAPI"
{
    // ... setup properties ...

    actions
    {
        area(Processing)
        {
            action(PostOrder)
            {
                Caption = 'Post Order';
                trigger OnAction()
                var
                    SalesHeader: Record "Sales Header";
                begin
                    // Logic to find and post the sales order
                end;
            }
        }
    }
}

By defining these actions, you provide a clean interface for external systems to interact with complex business processes without needing to understand the underlying implementation details of the posting routine.


Not read yet

Troubleshooting and Debugging

When your integration fails, the first step is to check the Business Central Web Service Requests page. This page logs all incoming API calls, including the URL, the user, the timestamp, and any error messages that were returned.

Debugging Tips:

  1. Check the logs: If a request fails, the error message in the Web Service Requests page will usually point you toward the specific line of AL code that caused the failure.
  2. Use Postman: Always test your API calls in Postman before writing the integration code in your external application. This isolates the API from your application code and allows you to quickly adjust your request body and headers.
  3. Review Permissions: If you are receiving 403 Forbidden errors, check that the user account associated with the OAuth token has the necessary permissions to access the specific pages and tables.
  4. Validate JSON: Use an online JSON validator to ensure your request body is correctly formatted before sending it to Business Central. A single missing comma or unmatched bracket will cause the request to fail.

Not read yet

Future-Proofing Your Integrations

The Business Central platform receives updates regularly. To ensure your integrations remain functional:

  • Monitor Release Notes: Microsoft publishes release notes for every major update. Check these for any changes to the API framework.
  • Use Versioned Endpoints: By using the versioning system in your API metadata, you can safely deploy new versions of your app without breaking the integrations that rely on the older, stable version.
  • Automated Testing: Implement automated tests for your API endpoints. If a future update to Business Central breaks your API, your tests will catch it immediately, allowing you to fix the issue before it impacts your production environment.

Key Takeaways for Success

Implementing APIs in Business Central is a journey from simple data exposure to complex process automation. By mastering the following points, you will be well-equipped to handle any integration requirement.

  1. Prioritize Custom APIs: Always prefer custom API pages over standard OData web services for new integrations. They offer better performance, cleaner data structures, and built-in versioning.
  2. Use OAuth 2.0: Never use basic authentication. OAuth 2.0 is the industry standard and ensures that your integrations are secure and compliant with modern enterprise security requirements.
  3. Think in Resources: Design your APIs around clear business entities. Use descriptive names and maintain a consistent structure across all your custom API groups.
  4. Implement Pagination: Never assume an API call will return a small amount of data. Always build your integrations to handle large datasets using $top and $skip to ensure stability.
  5. Enforce Business Logic: Ensure that your API endpoints respect the business logic defined in your tables and codeunits. An API should never bypass the integrity of your data.
  6. Test Thoroughly: Use tools like Postman to simulate real-world scenarios, including error handling, concurrency conflicts, and large data payloads.
  7. Document and Communicate: Keep your integration documentation up to date. A well-documented API is significantly easier to maintain and troubleshoot when issues arise.

Integrating Business Central with other applications is a powerful way to extend the capabilities of your ERP. By following these principles, you will create integrations that are not only functional but also scalable, secure, and easy to maintain over the long term. Start small, test often, and always keep the end-user experience in mind as you build your connected business ecosystem.


Not read yet

Frequently Asked Questions (FAQ)

Q: Can I access standard Business Central tables via APIs? A: Yes, Business Central provides a library of standard APIs that cover most common entities like Customers, Vendors, and Sales Orders. You can find these in the API documentation provided by Microsoft.

Q: How do I handle large file uploads via API? A: For large files, it is best to use a separate storage solution like Azure Blob Storage and then send a reference or URL to the file to Business Central via your API. Business Central is not designed to act as a high-volume file storage server.

Q: Is there a limit to how many API calls I can make? A: Yes, Business Central has request limits based on your subscription tier. If you find yourself hitting these limits, consider optimizing your requests to retrieve more data at once or implementing a queueing system to space out your requests.

Q: How do I handle updates to my API schema? A: You should use the APIVersion property. When you need to make a breaking change, increment the version number, publish the new version alongside the old one, and give your integration partners time to migrate to the new endpoint.

Q: Can I use API pages for read-only access? A: Absolutely. Simply set the Editable property to false on the page or on individual fields. This is a great way to provide reporting tools with access to your data without risking accidental modifications.

Not read yet

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