In today’s dynamic business landscape, organizations rely on a multitude of data sources to drive their operations. From external databases and data warehouses to online stores and services.

One of the easiest and most common ways of connecting them to Business Central is to use the APIs these sources of information provide. So, with some simple code, we can interact with external resources to exchange information.

  • HTTP Data Types
  • How To Call An API From Business Central?
  • Authentication
  • Response
  • Simple POST Request

HTTP Data Types


Business Central has 5 data types that allow these connections via AL language. We will have a look at them in detail, they are:

  • HttpClient. Responsible for sending and receiving the request.
  • HttpHeaders. The first part of the information for the message.
  • HttpContent. The second part of the information, it carries the content of the message.
  • HttpRequestMessage. The message that will be sent to the API.
  • HttpResponseMessage. The answer from the API that will be called.

You can declare them in AL like the following:


How To Call An API From Business Central?


One of the simplest calls we can create can be using one of the multiple open APIs that we can find on the internet. In this example, we are requesting information from the API for a cat fact.

This is an open API that everyone can connect to. Every service that offers APIs will provide some sort of documentation to allow developers to connect to them:

Cat Facts API

In this example, we just need 2 of the “HTTP” types. The HttpClient and HttpResponse are always compulsory in an HTTP request. And, of course, the URL or endpoint of the API. As you can see, we are using the GET method for requesting information.


If the connection was successful we will be able to see the response:


This is the most simple call one can make in Business Central. However, not all of them are like this. The example API doesn’t have authentication. But every secure API with confident data will indeed have.

In this cases, you’ll need some sort of credentials to access its data. Things get a little more complicated when we need to authenticate.

Authentication


There are several methods of authentication, basic, OAuth, etc. In the next example, you can see a way to use basic authentication.

We introduce 2 new types, HttpRequestMessage and HttpHeaders. They become fundamental when creating more complex API calls.

The way to build the call is quite simple:

  1. Set the information for the message
  2. Set the authorization in the header of the message
  3. Send the request
  4. Read and handle the response


The HttpRequestMessage has two main parts, HTTP headers and HTTP content.

The headers provide additional information about the request or response, such as the content type, language, caching instructions, authentication data, and more. They are used to control the behavior of the HTTP communication and to pass important data between the client and server.

We will learn more about the HTTP content in the following sections.

If the connection succeeds, you will receive the information from your response.


However, if something went wrong, due to invalid credentials, for example, ou will get a similar message:


There can be multiple reasons for a failed connection, the important thing is to detect what is failing based on the error message.

Nowadays, basic authentication is being deprecated. In Business Central, the authentication used to access its APIs is called OAuth. It’s similar to Basic, the only difference is that we need a token instead of a user and password.

A fast and easy way to test API connections is by using Postman. You can find a guide on how to use Postman with Business Central APIs here:


If you manage to connect with Postman, you should be able to do it from Business Central. If something goes wrong, you can see if it’s a problem with the Business Central call or the API endpoint.

Response


We received the response, but now we should be able to extract the information from it. The format in which we receive information is usually JSON in API requests, but it can also be XML.

A simple JSON type looks similar to the following image.


As mentioned above, you need to extract the information once the response is successful.


We have two ways of managing JSONs in Business Central, one is using the built-in types (JsonObject, JsonArray, etc) and the other is using the JSON buffer.

  • JsonObject.ReadFrom(). Gets the information into the JsonObject type.
  • JsonBuffer.ReadFromText(). Gets the information into the Json Buffer table.


If we show the result in the JSON buffer table we can see the information received.


Every HTTP response will have its own way of retrieving the data. If you’d like a post about handling JSON types let me know in the comment section below.


Code example for basic authentication.

    procedure HttpRequestWithBasicAuth(Url: Text[2048]; Username: Text[100]; Password: Text[100])
    var
        HttpClient: HttpClient;
        RequestMessage: HttpRequestMessage;
        ResponseMessage: HttpResponseMessage;
        RequestHeaders: HttpHeaders;
        Base64Convert: Codeunit "Base64 Convert";
        Response: Text;
        JsonObject: JsonObject;
        JsonBuffer: Record "JSON Buffer" temporary;
    begin
        RequestMessage.SetRequestUri(Url);
        RequestMessage.Method('GET');
        RequestMessage.GetHeaders(RequestHeaders);
        RequestHeaders.Add('Authorization', 'Basic ' + Base64Convert.ToBase64(Username + ':' + Password));
        if HttpClient.Send(RequestMessage, ResponseMessage) then begin
            ResponseMessage.Content.ReadAs(Response);
            if ResponseMessage.IsSuccessStatusCode then begin
                // Manage the response. Extract the information here.
                JsonObject.ReadFrom(Response);     // Built-in types

                JsonBuffer.ReadFromText(Response); // JSON Buffer
                Page.Run(Page::"JSON Buffer BCG", JsonBuffer);

            end else
                Message('Request failed!: %1', Response);
        end;
    end;


Simple POST Request


From the examples above you have learned to get information from an external database using the GET operation. Now, you will learn to insert into an external database with a simple POST method. The only difference between this request and the others is the information or content that we want to insert.

This is where we introduce the last of the HTTP types called HttpContent. What you have to do is mainly two things:

  • Set the body or information that you want to send.
  • Set the content type. In this case, we will use JSON.

We will insert an inventory item with No. BCG0001. For this, I created a very simple JSON. The JSON will be inserted with HttpContent.WriteFrom method.

For this example, we will have two new variables, HttpContent and ContentHeaders which is a new HttpHeader variable. As you can see we will are using two header types in total in this request.


If the connection succeeded we will get the response:


You can find more information about HTTP requests in the Microsoft documentation.

Call external services with the HttpClient data type – Business Central | Microsoft Learn

And here:

HttpClient Data Type – Business Central | Microsoft Learn

Make sure to go throw all the titles as you will find examples for GET, POST, DELETE, and PATCH operations. As well as detailed explanations for error handling.


Source code:

    procedure HttpRequestPOSTWithBasicAuth(Url: Text[2048]; Username: Text[100]; Password: Text[100])
    var
        HttpClient: HttpClient;
        RequestMessage: HttpRequestMessage;
        ResponseMessage: HttpResponseMessage;
        RequestHeaders: HttpHeaders;
        Base64Convert: Codeunit "Base64 Convert";
        Response: Text;
        JsonObject: JsonObject;
        JsonBuffer: Record "JSON Buffer" temporary;

        ContentHeaders: HttpHeaders;
        HttpContent: HttpContent;
    begin
        RequestMessage.SetRequestUri(Url);
        RequestMessage.Method('POST');
        RequestMessage.GetHeaders(RequestHeaders);
        RequestHeaders.Add('Authorization', 'Basic ' + Base64Convert.ToBase64(Username + ':' + Password));

        HttpContent.WriteFrom('{"number": "BCG0001","displayName": "BCG", "type": "Inventory"}');
        HttpContent.GetHeaders(ContentHeaders);
        ContentHeaders.Remove('Content-Type');
        ContentHeaders.Add('Content-Type', 'application/json');
        HttpContent.GetHeaders(ContentHeaders);
        RequestMessage.Content(HttpContent);

        if HttpClient.Send(RequestMessage, ResponseMessage) then begin
            ResponseMessage.Content.ReadAs(Response);
            if ResponseMessage.IsSuccessStatusCode then begin
                JsonBuffer.ReadFromText(Response);
                Page.Run(Page::"JSON Buffer BCG", JsonBuffer);
            end else
                Message('Request failed!: %1', Response);
        end;
    end;


In this post, you have learned to perform GET and POST operations to request and insert information to external sources using basic authentication. With the help of the HTTP data types, you have also learned to build methods that allow Business Central to communicate and interact with external databases. Along with handling the response in a JSON format.


That´s all. Hope you find it helpful.

How To Connect To External APIs From Business Central (HTTP Request)

Post navigation


17 thoughts on “How To Connect To External APIs From Business Central (HTTP Request)

  1. Very good and useful post.
    Please Keep posting on
    1) Handling Json.
    2) Steps of Generating Token in OAuth authentication method

  2. Hi, thanks for your sharing. when i tried to call api webservice from BC, i got a problem: error 401: unauthorized.

    I used BC on-prem, setup localhost. Do i need setting up something?
    my script:

    local procedure HttpRequest()
    var
    HttpClient: HttpClient;
    HttpResponseMessage: HttpResponseMessage;
    Response: Text;
    URL: label ‘http://xtr-thao:7048/BC200/api/v2.0/companies’;
    RequestHeaders: HttpHeaders;
    Base64Convert: Codeunit “Base64 Convert”;
    RequestMessage: HttpRequestMessage;
    ResponseMessage: HttpResponseMessage;
    begin
    if HttpClient.Get(URL, HttpResponseMessage) then begin
    HttpResponseMessage.Content.ReadAs(Response);
    Message(Response);
    end;
    end

  3. Hello , I have created a codeunit i al for business central to cal an API with reqeust body as the parameters ,but it is not working;see my code below and Kindly assist to correct me where necessary;codeunit 71706602 “Metropol Integration”
    {
    procedure GetIPRSData()
    var
    HttpClient: HttpClient;
    HttpHeaders: HttpHeaders;
    HttpContent: HttpContent;
    HttpRequestMessage: HttpRequestMessage;
    HttpResponseMessge: HttpResponseMessage;
    Url: Label ‘https://localhost:44382/metropol/reportscrub’;
    Response: Text[1000000];
    CustomerRec: Record Customer;
    IdentityNumber: Text[50];
    JsonRequest: Text;

    RequestMessage: HttpRequestMessage;
    ResponseMessage: HttpResponseMessage;
    RequestHeaders: HttpHeaders;
    ContentHeaders: HttpHeaders;

    Content: HttpContent;

    begin
    //JsonRequest := ‘{“report_type”:6,”identity_number”:”22176997″,”identity_type”:”001″}’;
    /*if (HttpClient.Get(Url, HttpResponseMessge)) then begin
    HttpResponseMessge.Content.ReadAs(Response);
    //Message(Response);
    Message(‘IPRS Data Retrieved Successfully’);
    end;*/
    JsonRequest := ‘{“report_type”:6,”identity_number”:”10043423″,”identity_type”:”001″}’;

    Content.GetHeaders(ContentHeaders);
    if ContentHeaders.Contains(‘Content-Type’) then ContentHeaders.Remove(‘Content-Type’);
    ContentHeaders.Add(‘Content-Type’, ‘multipart/form-data;boundary=boundary’);
    HttpRequestMessage.GetHeaders(RequestHeaders);
    RequestHeaders.Add(‘Accept’, ‘application/json’);
    RequestHeaders.Add(‘Accept-Encoding’, ‘utf-8’);
    RequestHeaders.Add(‘Connection’, ‘Keep-alive’);
    HttpRequestMessage.SetRequestUri(Url);
    HttpRequestMessage.Method(‘POST’);
    HttpContent.WriteFrom(JsonRequest);
    if (HttpClient.Post(Url, HttpContent, HttpResponseMessge)) then begin
    HttpResponseMessge.Content.ReadAs(Response);
    //Message(Response);
    Message(‘IPRS Data Retrieved Successfully’);
    end;
    end;
    }

  4. Thanks for the useful post.
    I have an API that requires a certificate for authentication. This certificate is a combination of the Cert PEM and Private Key PEM. Ideally this would be easy to consume the API through .NET but i cant figure out how i can using the AL certificate functionality to achieve the same.

    Have you encountered a similar problem? Could using Azure functions be the best way forward?

Leave a Reply

Your email address will not be published. Required fields are marked *