Sunday, May 24, 2020

Business Central Integration with Rest API – OnPrem - Part 1

Dear Reader’s, I am sharing simple REST API integration with Business Central 2020 Wave 1 release.

Business Central itself is more powerful and having wide range to methods stored in Codeunits to easily integrate to third party Application / System.

I am demonstrating with sample example how you will connect and read a REST API (JSON) data.

There is sample Open Weather Map API, URL: https://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b1b15e88fa797225412429c1c50c122a1 which I will use to demonstrate my example.

When you will paste this URL in browser, you will get below data in JSON format:

{"coord":{"lon":-122.09,"lat":37.39},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"base":"stations","main":{"temp":280.44,"pressure":1017,"humidity":61,"temp_min":279.15,"temp_max":281.15},"visibility":12874,"wind":{"speed":8.2,"deg":340,"gust":11.3},"clouds":{"all":1},"dt":1519061700,"sys":{"type":1,"id":392,"message":0.0027,"country":"US","sunrise":1519051894,"sunset":1519091585},"id":0,"name":"Mountain View","cod":200}

 

Copy this sample and paste in any of JSON formatter to understand the nodes, array & data in it. I have used jsonlint.com to format above data. You may chose as per your choice. So, below are formatted data looks like.

{

          "coord": {

                   "lon": -122.09,

                   "lat": 37.39

          },

          "weather": [{

                   "id": 500,

                   "main": "Rain",

                   "description": "light rain",

                   "icon": "10d"

          }],

          "base": "stations",

          "main": {

                   "temp": 280.44,

                   "pressure": 1017,

                   "humidity": 61,

                   "temp_min": 279.15,

                   "temp_max": 281.15

          },

          "visibility": 12874,

          "wind": {

                   "speed": 8.2,

                   "deg": 340,

                   "gust": 11.3

          },

          "clouds": {

                   "all": 1

          },

          "dt": 1519061700,

          "sys": {

                   "type": 1,

                   "id": 392,

                   "message": 0.0027,

                   "country": "US",

                   "sunrise": 1519051894,

                   "sunset": 1519091585

          },

          "id": 0,

          "name": "Mountain View",

          "cod": 200

}

 

From above sample, I will try to read below data thru AL codes:

          "main": {

                   "temp": 280.44,

                   "pressure": 1017,

                   "humidity": 61,

                   "temp_min": 279.15,

                   "temp_max": 281.15

          }

Now we have enough information & input to start our development. Here we go, below are steps:

Step 1: Update app.json file and add tag as "target": "OnPrem". Example

{
  "id""e43cc46f-a3fb-41f9-89c4-4c8cfcf84f38",
  "name""JsonAPITest",
  "publisher""Gaurav",
  "version""1.0.0.0",
  "brief""",
  "description""",
  "privacyStatement""",
  "EULA""",
  "help""",
  "url""",
  "logo""",
  "dependencies": [
    {
      "id""63ca2fa4-4f03-4f2b-a480-172fef340d3f",
      "publisher""Microsoft",
      "name""System Application",
      "version""16.0.0.0"
    },
    {
      "id""437dbf0e-84ff-417a-965d-ed2bb9650972",
      "publisher""Microsoft",
      "name""Base Application",
      "version""16.0.0.0"
    }
  ],
  "screenshots": [],
  "platform""16.0.0.0",
  "idRanges": [
    {
      "from"50100,
      "to"50149
    }
  ],
  "contextSensitiveHelpUrl""https://SocialMedia.com/help/",
  "showMyCode"true,
  "target""OnPrem",
  "runtime""5.0"
}

Step 2: Update settings.json and add "al.assemblyProbingPaths" with its path for assemblies. For example:

{
    "al.defaultLaunchConfigurationName""Your own server",
    "al.assemblyProbingPaths": [
        "./.netpackages",
        "C:/Windows/assembly/",
        "C:/Program Files/Microsoft Dynamics 365 Business Central/160/Service/Add-ins/"
    ]
}

Step 3: Build AL method to connect above URL and decode the desired output. I am using a codeunit to demonstrate the solution. You can copy the code and test the solution.


codeunit 50101 "Json API Test"
{
    trigger OnRun()
    begin
        Url := 'http://samples.openweathermap.org/data/2.5/weather?zip=110001,in&appid=b6907d289e10d714a6e88b30761fae22';
        HttpWebRequestMgt.Initialize(Url);
        HttpWebRequestMgt.DisableUI();
        HttpWebRequestMgt.SetMethod('GET');
        HttpWebRequestMgt.SetReturnType('application/json');

        Clear(TempBlob);
        TempBlob.CreateInStream(InStr);

        IF HttpWebRequestMgt.GetResponse(InStr, HttpStatusCode, ResponseHeader) then
            IF HttpStatusCode.ToString() = HttpStatusCode.OK.ToString() THEN begin
                InStr.ReadText(Json, MaxStrLen(Json));
                Message(Json);

                IF JSONMgmt.InitializeFromString(Json) then begin
                    Temperature := JSONMgmt.GetValue('main.temp');
                    Pressure := JSONMgmt.GetValue('main.pressure');
                    Humidity := JSONMgmt.GetValue('main.humidity');
                    TempMin := JSONMgmt.GetValue('main.temp_min');
                    TempMax := JSONMgmt.GetValue('main.temp_max');
                end;

                MESSAGE(Text001, Temperature, Pressure, Humidity, TempMin, TempMax);
            end;
    end;



    var
        HttpWebRequestMgt: Codeunit "Http Web Request Mgt.";
        Url: Text;
        Json: Text;
        TempBlob: Codeunit "Temp Blob";
        InStr: InStream;
        HttpStatusCode: DotNet HttpStatusCode;
        ResponseHeader: DotNet NameValueCollection;
        Temperature: Text;
        Pressure: Text;
        Humidity: Text;
        TempMin: Text;
        TempMax: Text;
        JSONMgmt: Codeunit "JSON Management";
        Text001: Label 'Temperature:%1\Pressure:%2\Humidity:%3\Min Temperature:%4\Max  Temperature: %5';
}

Step 4: Call this codeunit by extending any page. I am using customer card to extend and call this codeunit to display the message.

pageextension 50110 "CRONUS Social Media Card" extends "Customer Card"
{
    actions
    {
        addlast("&Customer")
        {
            Action(APITest)
            {
                ApplicationArea = All;
                Caption = 'API Test';
                Image = Web;
                // Run page to test how actions work
                RunObject = codeunit "Json API Test";
            }
        }
    }
}

That’s all folks. You may give a try. No matter you are using above codeunit in an action button or in a report or whatever you want.

Please share your feedback…


No comments:

Post a Comment