Getting and Sending Data to External Services

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

Getting and Sending Data to External Services: Integrating Business Central with REST APIs

Introduction: The Connected Enterprise

In the modern business landscape, no software application exists in a vacuum. Dynamics 365 Business Central is a powerful ERP system, but its true utility is unlocked when it talks to the rest of your organization’s ecosystem. Whether you are pushing sales orders to a third-party logistics provider, pulling real-time exchange rates from a financial service, or syncing customer data with a CRM, you are engaging in the practice of integration.

At the heart of these integrations is the REST (Representational State Transfer) architecture. REST services have become the industry standard for web communication because they are lightweight, scalable, and rely on the familiar HTTP protocol—the same language your web browser uses to load pages. Understanding how to access these services from within Business Central using AL (Application Language) is a critical skill for any developer or consultant working with the platform.

This lesson explores how to move data in and out of Business Central programmatically. We will move beyond the high-level concepts and dive into the mechanics of HTTP requests, authentication, payload formatting, and error handling. By the end of this module, you will be able to build resilient integrations that keep your business data flowing accurately across your infrastructure.


Not read yet

The Fundamentals of REST in AL

Before writing code, it is essential to understand the tools Business Central provides for web service communication. AL includes a set of native objects designed specifically for handling HTTP interactions. These objects reside in the System namespace and provide a structured way to build requests and parse responses.

The Key HTTP Objects

To interact with a REST API, you will primarily use four objects:

  1. HttpClient: This is the engine of your request. It manages the connection to the external service and is responsible for sending the request and receiving the response.
  2. HttpRequestMessage: This object acts as the container for your request. You define the URL, the HTTP method (GET, POST, PUT, DELETE), and the headers here.
  3. HttpResponseMessage: Once the HttpClient finishes its task, it returns this object. It contains the status code, the response headers, and the body (the actual data) returned by the server.
  4. HttpContent: This object is used to represent the payload (the data) you are sending to the server, typically formatted as JSON or XML.

Callout: Why REST? REST is favored over older protocols like SOAP because it is stateless and resource-oriented. While SOAP requires strict adherence to a WSDL (Web Service Description Language) and uses envelope-style XML, REST allows you to use standard HTTP verbs—GET to read, POST to create, PUT to update, and DELETE to remove. This simplicity reduces overhead and makes debugging significantly easier when issues arise in your integration.


Not read yet

Step-by-Step: Consuming a GET Request

A GET request is the most common operation. You use it to retrieve information from an external service, such as fetching a shipping status or a product catalog from a vendor.

Implementation Process

  1. Initialize the Objects: Create instances of HttpClient, HttpRequestMessage, and HttpResponseMessage.
  2. Configure the Request: Set the request method to 'GET' and assign the target URL.
  3. Set Headers: If the API requires an API key or authentication token, add it to the headers.
  4. Send the Request: Invoke the Send method of the HttpClient.
  5. Process the Response: Verify the status code and read the content.

Code Example: Fetching External Data

procedure GetExternalData()
var
    Client: HttpClient;
    Request: HttpRequestMessage;
    Response: HttpResponseMessage;
    ResponseText: Text;
    TargetUrl: Label 'https://api.example.com/v1/products';
begin
    // Initialize the request
    Request.SetRequestUri(TargetUrl);
    Request.Method := 'GET';

    // Add authentication header
    Request.Headers.Add('Authorization', 'Bearer YOUR_TOKEN_HERE');
    Request.Headers.Add('Accept', 'application/json');

    // Send the request
    if Client.Send(Request, Response) then begin
        if Response.IsSuccessStatusCode then begin
            Response.Content.ReadAs(ResponseText);
            // Handle the response text here
            Message('Data received: %1', ResponseText);
        end else begin
            Error('Server returned error: %1', Response.HttpStatusCode);
        end;
    end else begin
        Error('The connection to the service failed.');
    end;
end;

Note: Always check Response.IsSuccessStatusCode before attempting to read the response body. If the server returns a 404 or 500 error, the body might contain an error message, but it will not be the data you expect. Attempting to parse an error page as JSON will cause your code to crash.


Not read yet

Step-by-Step: Sending Data with a POST Request

A POST request is used when you need to send data to an external system to create or trigger an action. This is common when pushing a sales order from Business Central to an external warehouse management system (WMS).

Handling JSON Payloads

When sending data, you must serialize your AL objects into a JSON string. The JsonObject and JsonToken data types in AL are essential for this purpose.

Code Example: Sending a JSON Object

procedure SendDataToExternalService()
var
    Client: HttpClient;
    Request: HttpRequestMessage;
    Response: HttpResponseMessage;
    Content: HttpContent;
    JsonObj: JsonObject;
    JsonText: Text;
begin
    // Build the JSON payload
    JsonObj.Add('OrderId', 'SO-1001');
    JsonObj.Add('Customer', 'John Doe');
    JsonObj.WriteTo(JsonText);

    // Prepare the content
    Content.WriteFrom(JsonText);
    Content.GetHeaders(Headers);
    Headers.Remove('Content-Type');
    Headers.Add('Content-Type', 'application/json');

    // Prepare the request
    Request.SetRequestUri('https://api.example.com/orders');
    Request.Method := 'POST';
    Request.Content := Content;

    // Send the request
    if Client.Send(Request, Response) then begin
        if Response.IsSuccessStatusCode then
            Message('Order sent successfully.')
        else
            Error('Failed to send order. Status: %1', Response.HttpStatusCode);
    end;
end;

Not read yet

Best Practices for Integration

Integrations are often the most fragile part of an ERP implementation. Following these best practices will help you build robust systems that survive the unpredictability of the internet.

1. Implement Timeout Management

By default, an HTTP request might hang if the remote server is unresponsive. Always set a timeout on your HttpClient to ensure your Business Central process doesn't lock up indefinitely.

Client.DefaultRequestHeaders.Add('Timeout', '30000'); // 30 seconds

2. Use Named Labels for URLs

Never hardcode URLs directly inside your functions. Use Label objects or, even better, store your integration endpoints in a "Setup" table. This allows you to change the endpoint (e.g., from a sandbox URL to a production URL) without modifying code.

3. Log Everything

When things go wrong, you need a trail. Create a custom log table in Business Central to store the request URL, the payload, the timestamp, and the response code/body for every integration attempt. This is invaluable when a user claims an order wasn't sent, but you can prove it was sent at 2:15 PM and the server returned a 401 Unauthorized error.

4. Secure Sensitive Data

Never store hardcoded API keys or client secrets in your source code. Use the Isolated Storage module to store sensitive credentials. This keeps your secrets encrypted and inaccessible to other extensions or users.

5. Handle Errors Gracefully

Integration points are prone to network blips. Implement a retry mechanism for transient errors (like 503 Service Unavailable). If a request fails, log the error and notify an administrator rather than simply failing silently or stopping the entire business process.


Not read yet

Common Pitfalls and How to Avoid Them

Even experienced developers encounter issues when working with external REST services. Here are the most frequent mistakes:

  • The "Double-Encoding" Trap: When building JSON manually using strings, developers often escape characters incorrectly. Always use the built-in JsonObject and JsonArray types. They handle the serialization and character escaping automatically, preventing malformed JSON.
  • Ignoring Content-Type Headers: Many APIs will reject your request if you do not explicitly state the Content-Type as application/json. If you omit this, the server may default to text/plain, causing the API to reject the request as invalid.
  • Over-reliance on Synchronous Calls: Business Central is a transactional system. If you perform a slow HTTP call inside a OnAfterInsert trigger, you will force the user to wait for the web service to respond before they can continue. For heavy integrations, consider using a Job Queue to process the data asynchronously in the background.
  • Forgetting about Character Encoding: Ensure your content is encoded as UTF-8. While AL handles this well by default, if you are reading data from legacy systems, you might encounter issues with special characters (like symbols or non-English letters).

Not read yet

Comparison: AL Integration Options

Beyond writing custom HTTP code, Business Central offers several ways to integrate. Understanding when to use which is key to a clean architecture.

Feature Custom HTTP Code API Pages Power Automate
Complexity High Low Very Low
Control Full Partial Limited
Performance High High Moderate
Best For Complex logic/Custom APIs Exposing BC data Workflow automation

Callout: Custom Code vs. API Pages Use custom HTTP code when you need to act as a client (talking to an external service). Use API Pages when you need to act as a server (letting an external service talk to you). If you are building an integration, clarify your direction of communication before you start coding.


Advanced Topic: Authenticating with OAuth2

Most modern APIs require OAuth2 authentication. This is more complex than a simple API key because it involves an exchange of tokens. The process usually follows these steps:

  1. Request an Access Token: You send your Client ID and Client Secret to an authorization server.
  2. Receive the Token: The server returns a JSON object containing an access_token.
  3. Use the Token: Include this token in the Authorization header for all subsequent API requests.
  4. Refresh: If the token expires, use a refresh_token to get a new one without asking the user for credentials again.

Managing this logic manually is tedious. Fortunately, Business Central provides the OAuth2 module in the system library, which simplifies the token acquisition process. Use this module whenever possible rather than writing your own manual token-handling logic, as it includes built-in security features and token lifecycle management.


Not read yet

Troubleshooting Integration Issues

When an integration fails, the first step is to isolate the problem. Is the issue in the request construction, the authentication, or the server's processing?

Step-by-Step Debugging Strategy

  1. Test in Postman: Take the exact URL, headers, and body you are using in your AL code and test them in a tool like Postman. If it fails there, the issue is with the API endpoint or your credentials, not your AL code.
  2. Inspect the Request: Use the HttpRequestMessage object to inspect the headers before sending. Ensure the Authorization header is present and correctly formatted (e.g., "Bearer [token]").
  3. Check the Response Body: If the server returns a 400 Bad Request, the body often contains a detailed error message explaining exactly which field in your JSON was incorrect. Read this body into a text variable and display it in your error message.
  4. Check the Network: If you get a "Connection Timeout," check if your Business Central environment is allowed to communicate with the target URL. If you are using a cloud-based environment, ensure the target service is not blocked by a firewall that requires a specific IP range.

Not read yet

Practical Exercise: Syncing a Customer

To solidify your knowledge, try the following exercise:

  1. Create a Codeunit that triggers when a Customer record is modified.
  2. In the OnAfterModify trigger, capture the Customer's Name and Email.
  3. Format this data into a JSON object.
  4. Send this JSON to a dummy endpoint (you can use a service like webhook.site for testing).
  5. If the response code is 200, display a message to the user confirming the sync. If it fails, log the error to a custom table.

This exercise covers the entire lifecycle of an integration: capturing the event, preparing the data, executing the request, and handling the outcome.


Conclusion and Key Takeaways

Integrating Business Central with external REST services is a foundational skill that transforms the ERP from a siloed database into a core component of a connected business. By mastering the HttpClient and associated objects, you gain the ability to extend the functionality of your system well beyond its native capabilities.

Key Takeaways:

  • HTTP Objects are Standard: Always use HttpClient, HttpRequestMessage, and HttpResponseMessage for consistent, reliable communication.
  • Prioritize JSON: Use JsonObject and JsonToken to handle data serialization. Manual string manipulation for JSON is a recipe for bugs and security vulnerabilities.
  • Security First: Never hardcode credentials. Utilize Isolated Storage and the OAuth2 module to keep your integrations secure and compliant.
  • Error Handling is Mandatory: Assume the network will fail. Always check response codes and implement logging for every integration point.
  • Performance Matters: Avoid blocking the user interface with slow synchronous calls. Offload heavy processing to the Job Queue when necessary.
  • Test Before You Code: Use tools like Postman to verify API behavior before writing your AL implementation.
  • Keep It Simple: Don't over-engineer your integrations. If a standard API page can expose your data, use that instead of building a complex custom web service.

As you continue your journey in Business Central development, remember that the goal of integration is to remove friction. A well-built integration should be invisible to the end-user, running silently in the background to ensure that data is accurate and available exactly where it is needed. By following these principles, you will be able to build integrations that are not only functional but also maintainable and secure for the long term.


Not read yet

Common Questions (FAQ)

Q: Can I use Business Central to connect to an API that uses XML instead of JSON? A: Yes. While JSON is the standard for REST, you can send and receive XML by setting the Content-Type header to application/xml and using the XmlDocument object in AL to parse the response.

Q: How do I handle large amounts of data? A: If you need to sync thousands of records, do not do it in a single loop. Use pagination (if the API supports it) and break the work into smaller batches. This prevents timeout errors and ensures your transaction logs remain manageable.

Q: What if the external service is down? A: You should design your integration to be "idempotent" where possible. This means if you send the same request twice, it doesn't cause errors or duplicate data. Furthermore, always have a strategy to re-queue failed requests so that data can be synchronized once the service returns.

Q: Are there limits to how many requests I can make? A: Yes, every API has rate limits. Check the documentation of the service you are consuming. If you hit those limits, your integration will start receiving 429 Too Many Requests errors. You may need to implement a delay or throttling logic in your code to stay within the allowed limits.

Not read yet

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