Using HTTP Classes and Functions

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

Lesson: Accessing REST Services in Business Central Using HTTP Classes

Introduction: Why Connectivity Matters in Business Central

In the modern business landscape, no software application exists in a vacuum. Dynamics 365 Business Central is a powerful ERP system, but its true potential is unlocked only when it can "talk" to other services—whether that is a local shipping carrier’s API, a CRM system, a tax calculation engine, or a cloud-based document storage service. When we talk about "accessing REST services," we are talking about the ability of Business Central to reach out, request data, or push information to external systems using standard web protocols.

Understanding how to use HTTP classes and functions within Business Central’s AL (Application Language) is a fundamental skill for any developer or consultant. Without this knowledge, you are limited to the data that exists inside your tenant. With it, you can create automated workflows that bridge the gap between your ERP and the rest of your digital ecosystem. This lesson will guide you through the core components of the HTTP request lifecycle, how to structure your code for reliability, and how to handle the data that comes back from external services.

Not read yet

Core Concepts: The HTTP Request Lifecycle

Every interaction with a REST API follows a predictable pattern. It starts with the client (your Business Central environment) initiating a request to a server. This request includes a specific action (the verb), a destination (the URL), and often some metadata (the headers) or a payload (the body). The server processes this request and returns a response, which contains a status code and, usually, a payload.

In AL, we use a specific set of objects to manage this lifecycle. These are not just simple functions; they are full objects that carry state and configuration. The primary objects we work with are:

  • HttpClient: The engine that sends the request and receives the response.
  • HttpRequestMessage: The container that holds the destination, the method, and the headers.
  • HttpResponseMessage: The container that holds the server’s reply, including status codes and the actual data content.
  • HttpContent: The object used to represent the payload of a request or a response.
  • HttpHeaders: A collection of key-value pairs used to pass metadata, such as authentication tokens or content-type definitions.

By mastering these five objects, you can interact with almost any web service that follows standard REST principles.

Callout: The Difference Between Sync and Async In some programming environments, HTTP requests are asynchronous, meaning the code continues running while the request happens in the background. In Business Central AL, HTTP requests are synchronous. This means the execution of your code stops and waits for the server to reply. While this makes the logic easier to follow, it also means you must be careful about performance; a slow external API will directly cause a slow experience for your user.

Not read yet

Step-by-Step: Constructing a Simple GET Request

A GET request is the most common interaction. It is used to "read" data from a remote service. To perform a GET request, you need to follow a sequence of steps that ensures the request is correctly formed and that you handle potential errors gracefully.

Step 1: Initialize the Objects

You must declare your variables before you can use them. Always remember to clear these variables if you are reusing them within a loop or a complex process to avoid memory leaks or data contamination.

Step 2: Configure the Request

You define the URL and the HTTP method (GET, POST, PUT, DELETE). You also set any necessary headers, such as 'Accept' or 'Authorization'.

Step 3: Send the Request

Using the HttpClient object, you call the Send or Get function to transmit your message to the destination.

Step 4: Validate the Response

Never assume a request was successful. Always check the IsSuccessStatusCode property of the HttpResponseMessage before attempting to read the content.

Code Example: Fetching External Data

procedure GetExternalData(Url: Text)
var
    Client: HttpClient;
    Response: HttpResponseMessage;
    Content: HttpContent;
    ResultText: Text;
begin
    // Initialize the client
    if not Client.Get(Url, Response) then
        Error('The call to the web service failed.');

    // Check if the server returned a 2xx status code
    if Response.IsSuccessStatusCode then begin
        Response.Content.ReadAs(ResultText);
        Message('The data received is: %1', ResultText);
    end else begin
        Error('The web service returned an error: %1 - %2', 
              Response.HttpStatusCode, Response.ReasonPhrase);
    end;
end;

Note: In the example above, we use Client.Get. This is a shorthand method. If you need to add custom headers (like an API Key), you must use the HttpRequestMessage object instead of the shorthand Get method.

Not read yet

Advanced Request Handling: Using HttpRequestMessage

When working with real-world APIs, you rarely send a simple, unauthenticated GET request. Most APIs require an API key, a Bearer token, or a specific content type (like application/json). To do this, you must explicitly construct the HttpRequestMessage.

Adding Headers

Headers are the "envelope" of your message. You add them to the HttpRequestMessage object. Common headers include Authorization, Content-Type, and Accept.

Setting the Content

When you send data (like creating a new record in an external system), you need to populate the HttpContent object. This requires taking your data (usually a JSON object), converting it to a string, and then attaching it to the request.

Code Example: Sending a JSON Payload

procedure PostDataToService(Url: Text; JsonPayload: Text)
var
    Client: HttpClient;
    Request: HttpRequestMessage;
    Response: HttpResponseMessage;
    Content: HttpContent;
    Headers: HttpHeaders;
begin
    // 1. Set the Request Method and URL
    Request.Method := 'POST';
    Request.SetRequestUri(Url);

    // 2. Set the Content
    Content.WriteFrom(JsonPayload);
    Content.GetHeaders(Headers);
    Headers.Remove('Content-Type');
    Headers.Add('Content-Type', 'application/json');
    Request.Content := Content;

    // 3. Send the Request
    if not Client.Send(Request, Response) then
        Error('The request could not be sent.');

    // 4. Handle the Response
    if not Response.IsSuccessStatusCode then
        Error('API returned error: %1', Response.HttpStatusCode);
end;

Not read yet

Best Practices for API Integration

Building a robust integration requires more than just making the code work once. You must account for the reality that networks fail, servers go down, and data formats change.

1. Error Handling and Logging

Business Central provides excellent tools for logging, but you should also build your own error-handling logic. If an API call fails, don't just throw a generic error. Log the status code, the reason phrase, and, if possible, the body of the response. This makes troubleshooting significantly easier when a user reports a failure.

2. Timeouts

By default, an HTTP request will wait for a response for a specific amount of time. If the external service is sluggish, your Business Central session might hang. You can configure the Timeout property on the HttpClient object. Always set a reasonable timeout to ensure the user experience remains acceptable.

3. Security and Credentials

Never hardcode API keys or passwords directly in your AL code. This is a massive security risk. Instead, use the Azure Key Vault integration or the Isolated Storage feature in Business Central. These allow you to store sensitive credentials securely and retrieve them at runtime.

4. Payload Optimization

Only send the data that is required. If you are updating a customer record in an external CRM, do not send the entire customer object if the API only needs the ID and the phone number. Reducing the payload size decreases the time spent on serialization and transmission, leading to faster integrations.

5. Idempotency

When designing integrations, consider what happens if a network glitch occurs. If you send a "Create" request and the connection drops before you get a confirmation, did the record get created? If you send it again, will you get a duplicate? Whenever possible, use APIs that support idempotency keys, which allow you to safely retry requests without creating duplicate records.

Callout: The Power of JSON REST APIs almost exclusively use JSON for data exchange. In Business Central, you should become very comfortable with the JsonObject, JsonArray, JsonToken, and JsonValue types. These types allow you to programmatically build, parse, and manipulate complex data structures without having to perform manual string manipulation, which is error-prone.

Not read yet

Common Pitfalls and How to Avoid Them

Even experienced developers run into common issues when working with HTTP services. Being aware of these will save you hours of debugging.

Pitfall 1: SSL/TLS Version Mismatch

Business Central runs in a secure, cloud-based environment. It requires that the external service you are connecting to supports modern, secure encryption protocols (TLS 1.2 or higher). If you try to connect to a legacy server using an outdated protocol, the connection will be rejected by the Business Central platform before it even reaches the server.

Pitfall 2: Forgetting to Clear Content

When you reuse an HttpContent object in a loop, the previous content might persist. Always re-instantiate or clear your content objects inside your loop to ensure each request starts with a clean slate.

Pitfall 3: Not Handling JSON Parsing Errors

When reading a response, developers often assume the body will be a perfectly formatted JSON string. If the server returns a 500 error, it might return an HTML page or plain text instead of JSON. Always check the response status code before passing the response body into a JSON parser.

Pitfall 4: Ignoring Character Encoding

When working with international data, character encoding matters. Always ensure that your HttpContent is using UTF-8 encoding. Most modern REST services expect this, and failing to set it explicitly can lead to corrupted data or "mojibake" (garbled text).

Not read yet

Comparison: HttpClient vs. WebRequest (Legacy)

In older versions of Dynamics NAV, developers used the System.Net.WebRequest .NET interop. While this is still technically possible in some on-premises scenarios, it is strictly forbidden in the cloud.

Feature HttpClient (Modern AL) WebRequest (.NET Interop)
Cloud-Ready Yes No
Performance Optimized for SaaS Heavy overhead
Ease of Use High (Native AL) Low (Requires .NET knowledge)
Security Managed by Platform Manual configuration
Maintainability High Low

Always prioritize the native HttpClient classes. They are designed specifically for the Business Central runtime and benefit from ongoing performance and security updates provided by Microsoft.

Step-by-Step: Debugging an Integration

When your integration isn't working, follow this systematic approach to isolate the issue:

  1. Check the Status Code: Is the error a 401 (Unauthorized)? A 404 (Not Found)? A 500 (Server Error)? The status code is your first and most important clue.
  2. Inspect the Headers: Use a tool like Postman or curl to test the API endpoint independently of Business Central. If it works in Postman but not in AL, compare your headers. You might be missing a required User-Agent or Accept header.
  3. Review the Body: If the server returns an error, it usually includes a JSON body explaining the error. Read this body into a string and log it to a variable so you can view it in the debugger.
  4. Check Network Access: If you are using an on-premises Business Central environment, ensure the server has outbound internet access and is not blocked by a firewall. If you are using the cloud, remember that you may need to whitelist the Business Central service IP addresses on the external API's firewall.
  5. Use the Debugger: Set breakpoints in your AL code right before the Client.Send call. Inspect the Request object to verify that the URL, headers, and content are exactly what you intend to send.

Not read yet

Advanced Scenario: Handling Authentication

Authentication is usually the most complex part of an integration. Here are the three most common patterns you will encounter:

Pattern 1: API Key in Header

This is the simplest form. You simply add a header with your key.

Headers.Add('X-API-Key', 'your-secret-key-here');

Pattern 2: Basic Authentication

This requires a Base64 encoded string of your username and password.

var
    AuthString: Text;
    Base64: Codeunit "Base64 Convert";
begin
    AuthString := StrSubstNo('%1:%2', Username, Password);
    Headers.Add('Authorization', 'Basic ' + Base64.ToBase64(AuthString));
end;

Pattern 3: OAuth2

This is the industry standard. You first request a token from an identity provider, and then you use that token in the Authorization header of your subsequent requests. Business Central provides a dedicated OAuth2 codeunit that simplifies this process, handling the token refresh logic for you. Always use the built-in OAuth2 codeunit rather than building your own token management system.

Not read yet

Designing for Failure: The "Circuit Breaker" Pattern

In highly critical integrations, you might want to implement a "Circuit Breaker" pattern. If an external service fails repeatedly, the circuit "trips," and your code stops attempting to call the service for a set period. This prevents your Business Central system from wasting resources on a service that is clearly down and protects the external service from being hammered by retry attempts while it is struggling to recover.

To implement this in AL:

  • Use a table to store the state of the service (e.g., ServiceUp boolean and LastFailureTime).
  • Before every call, check the table. If the service is marked as "Down" and the LastFailureTime is within the last 5 minutes, skip the call and notify the administrator.
  • If the call is successful, reset the status to "Up."

This level of maturity in your integrations distinguishes professional-grade solutions from simple scripts.

Not read yet

Summary Checklist for Developers

Before you deploy any integration code to production, run through this mental checklist:

  1. Authentication: Are my credentials stored securely (Key Vault/Isolated Storage)?
  2. Error Handling: Am I checking IsSuccessStatusCode and logging the response body on failure?
  3. Timeouts: Is my HttpClient.Timeout set to a sensible value?
  4. Logging: Does my code log the request and response in a way that allows for easy debugging?
  5. Performance: Am I calling the API inside a loop? If so, can I batch the requests instead?
  6. Security: Am I using HTTPS for all requests?
  7. Data Validation: Am I parsing the JSON response safely, checking for the existence of keys before accessing them?

Key Takeaways

  1. Understand the Lifecycle: The HttpClient, HttpRequestMessage, and HttpResponseMessage objects are the pillars of all REST communication in AL. Mastering their lifecycle is the first step.
  2. Always Validate Responses: Never assume a request succeeded. Always check IsSuccessStatusCode and handle non-200 responses explicitly.
  3. Security First: Never hardcode secrets. Utilize Azure Key Vault or Isolated Storage to manage API keys and tokens.
  4. Use Modern Tools: Stick to the native HttpClient and JSON objects provided by the AL language rather than legacy interop methods.
  5. Think About Reliability: Real-world networks are unreliable. Implement logging, timeouts, and thoughtful error handling to ensure your integration can survive transient network issues.
  6. Efficiency Matters: Keep payloads small and minimize the number of round-trips to the server. Batching is your best friend when dealing with large datasets.
  7. Test Thoroughly: Use external tools like Postman to verify API behavior before writing the AL code, and always test your error handling paths by simulating service outages.

By following these guidelines, you will be able to build robust, secure, and maintainable integrations between Business Central and the vast array of web services that power modern business. Remember, the goal is not just to make it work, but to make it work reliably under the unpredictable conditions of the real world.

Not read yet

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