Showing posts with label #BCIntegration. Show all posts
Showing posts with label #BCIntegration. Show all posts

Saturday, December 19, 2020

GST E-Invoice API Integration Explained

Dear Reader, GSPs/ASPs & Dynamics NAV Service Provider/Consultants are too busy to integrate E-Invoice solutions. Taxpayers with Turnover between Rs 100 Cr- Rs 500 Cr can contact the GSP / ERPs for the willingness to integrate the e-Invoice APIs through them.

Lots of solutions being offered. Customers are in rush to get it done ASAP as dead line is approaching.

Mostly solution are opted by customer:

  1. API : Plain Text  
  2. API : With Encryption & Decryption
  3. SFTP file transfer (Excel/CSV/JSON)
Further solutions are offered with two type of schema:
  1. GSP's own schema
  2. Government Compatible
Below I am explaining solution step by step, how to integrate E-Invoice APIs.

Hope all of us are aware about Microsoft has already given solution (can be checked in recent Cumulative updates & can be found on Posted Sales Invoice / Credit Memo):
  1. Generate IRN
  2. Export Json File
  3. Import Json File
There is a codeunit ID; 16511 with Name: e-Invoice, for export & import JSON request & response based on Government Schema (based on NIC portal & can be checked here). Which is provided by Microsoft to export & import Json files.

So, not need to create external solution (eg. DLLs for calling API & parsing received response). API request & response can be done in NAV only using NAV Codeunits & standard .net variables of Windows .net framework & NAV add-ins.

Creating outside solution will require extra maintenance. You need to update your DLL, place DLL in add-in folder & update your NAV codes. Making such solution, you are making customer highly dependent. So, its better to write code natively in NAV for API call & response parsing which can be easily updated & deployed. 

Below are major steps to reuse NAV existing solutions:

Step 1: We have already solution available to prepare JSON structure with required data. We need to reuse this solution to fit into GSP's own schema or Govt. compatible schema. It's easy & quick to modify given Codeunit 16511 or can save in available Codeunit's ID of customer's license with different name. For example Codeunit ID: 50005 Name: e-Invoice Management.

Step 2: Create a Setup table to store GSP's API URLs & Credentials, etc. For example:


Note: You may add/modify filed as per GSP details. Create a corresponding page for this table.

Step 3: Create a log/entry table to store API request & response status & details. For Example: e-Invoice Entry


Note: Above fields are for example only. You may add/modify as per your need. Create a corresponding page for this table.

Step 4: Modify e-Invoice Management codeunit's methos "ExportAsJson(DocumentNo);" to call API & process response. Get the e-Invoice Setup and check if Integration is enabled then Call API otherwise leave the original code to save the JSON file. 

Define the below variables in function "ExportAsJson":

 Update "ExportAsJson" function as below:

 LOCAL PROCEDURE ExportAsJson@1500012(DocumentNo@1500000 : Code[20]);

    VAR

      NewStream@1055602 : InStream;
      HttpWebRequestMgt@1170000000 : Codeunit 1297;
      TempBlob@1170000003 : Record 99008535;
      HTTPStatusCode@1170000002 : DotNet "'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.HttpStatusCode";
      ResponseHeader@1170000001 : DotNet "'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Collections.Specialized.NameObjectCollectionBase";
      InStr@1170000004 : InStream;
      Json@1170000005 : Text;
      JSONManagement@1170000006 : Codeunit 5459;
      WasSuccess@1170000007 : Boolean;
      ErrorText@1170000008 : Text;
      TrnsIdentifier@1170000009 : Text[250];
      AckNumber@1170000014 : Text[30];
      AckDateText@1170000015 : Text[30];
      IRNText@1170000010 : Text[250];
      SignedQR@1170000011 : Text;
      SignedInv@1170000012 : Text;     
      eInvoiceEntry@1170000016 : Record 50051;
      OStream@1170000017 : OutStream;
      RequestText@1170000018 : Text;
      QRPayload@1000000001 : Text;
      IRNStatus@1000000002 : Text;
      eInvoiceSetup@1000 : Record 50050;
      AuthToken@1004 : Text[250];
      SuccessText@1000000004 : Text[10];
      QRCodeFileName@1000000005 : Text;
      FileMgmt@1000000006 : Codeunit 419;
                  ArrayString@1000000009 : Text; 
      JObject@1000000008 : DotNet "'Newtonsoft.Json'.Newtonsoft.Json.Linq.JObject";
      JSONArray@1000000007 : DotNet "'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'.Newtonsoft.Json.Linq.JArray";
      RequestResponse@1000000010 : BigText;
    BEGIN
      eInvoiceSetup.GET();
               IF eInvoiceSetup."Integration Enabled" THEN BEGIN 
                               
      HttpWebRequestMgt.Initialize(eInvoiceSetup."Base URL" + eInvoiceSetup."
Generate E-Invoice URL");
      HttpWebRequestMgt.DisableUI();
      HttpWebRequestMgt.SetMethod('POST');
                         //Write similar function to get the Auth Token
      HttpWebRequestMgt.AddHeader('Bearer', AuthToken);
      HttpWebRequestMgt.SetContentType('application/json');
      HttpWebRequestMgt.SetReturnType('application/json');
                         RequestText := FORMAT(StringBuilder.ToString); 
      HttpWebRequestMgt.AddBodyAsText(RequestText);
      
      WasSuccess := FALSE;
      ErrorText := '';
      IRNText := '';
      SignedQR := '';
      SignedInv := '';
       AckNumber := '';
      QRPayload := '';
      IRNStatus := '';
      TempBlob.INIT;
      TempBlob.Blob.CREATEINSTREAM(InStr);
      IF HttpWebRequestMgt.GetResponse(InStr,HTTPStatusCode,ResponseHeader) THEN BEGIN
        IF FORMAT(HTTPStatusCode.ToString) IN ['OK','Ok','ok'] THEN
          WasSuccess := TRUE;
          Json := TempBlob.ReadAsText('',TEXTENCODING::UTF8);
          
          JSONManagement.InitializeFromString(Json);
          SuccessText := JSONManagement.GetValue('Success');
          IF UPPERCASE(SuccessText) = 'Y' THEN BEGIN
            AckNumber := JSONManagement.GetValue('AckNo');
            AckDateText := JSONManagement.GetValue('AckDt');
            IRNText := JSONManagement.GetValue('Irn');
            SignedInv := JSONManagement.GetValue('SignedInvoice');
            SignedQR := JSONManagement.GetValue('SignedQRCode');
            IRNStatus := JSONManagement.GetValue('Status');
          END ELSE BEGIN
            JObject := JObject.JObject();
            JSONManagement.GetJSONObject(JObject);
            ArrayString := JObject.SelectToken('ErrorDetails').ToString;
            CLEAR(JSONManagement);
            CLEAR(JObject);
            JObject := JObject.JObject();
            JSONArray := JSONArray.JArray();
            JSONManagement.InitializeCollection(ArrayString);
            JSONManagement.GetJsonArray(JSONArray);
            FOREACH JObject IN  JSONArray DO BEGIN
              ErrorText := JObject.GetValue('error_message').ToString;
            END
          END;
      END ELSE
        SuccessText := 'N';
 
      //Create Entry
      eInvoiceEntry.INIT;
      IF IsInvoice THEN
        eInvoiceEntry."Document Type" := eInvoiceEntry."Document Type"::Invoice
      ELSE
        eInvoiceEntry."Document Type" := eInvoiceEntry."Document Type"::CrMemo;
      eInvoiceEntry."Document No." := DocumentNo;
      
      CLEAR(RequestResponse);
      RequestResponse.ADDTEXT(RequestText);
      eInvoiceEntry."Request JSON".CREATEOUTSTREAM(OStream);
      RequestResponse.WRITE(OStream);
      
      CLEAR(RequestResponse);
      RequestResponse.ADDTEXT(Json);
      eInvoiceEntry."Response JSON".CREATEOUTSTREAM(OStream);
      RequestResponse.WRITE(OStream);
     
      IF NOT eInvoiceEntry.INSERT THEN
        eInvoiceEntry.MODIFY;
     
      IF UPPERCASE(SuccessText) = 'Y' THEN BEGIN
        QRCodeFileName := GetQRCode(SignedQR);
        QRCodeFileName := MoveToMagicPath(QRCodeFileName); // To avoid confirmation dialogue on RTC
        CLEAR(TempBlob);
        FileMgmt.BLOBImport(TempBlob,QRCodeFileName);
        IF TempBlob.Blob.HASVALUE THEN BEGIN
          eInvoiceEntry."QR Code Image" := TempBlob.Blob;
        END;
        eInvoiceEntry.Status := eInvoiceEntry.Status::Generated;
        eInvoiceEntry."Acknowledgment No." := AckNumber;
        eInvoiceEntry."Acknowledgment Date" := AckDateText;
        eInvoiceEntry.IRN := IRNText;
        eInvoiceEntry."IRN Status" := IRNStatus;
        eInvoiceEntry.SignedQRWriteAsText(SignedQR,TEXTENCODING::UTF8);
        eInvoiceEntry.SignedInvWriteAsText(SignedInv,TEXTENCODING::UTF8);
        eInvoiceEntry."QR Code".CREATEOUTSTREAM(OStream,TEXTENCODING::UTF8);
        OStream.WRITETEXT(QRPayload,STRLEN(QRPayload));
      END ELSE BEGIN
        eInvoiceEntry.Status := eInvoiceEntry.Status::Fail;
        eInvoiceEntry."Error Message" := COPYSTR(ErrorText,1,250);
      END;
      eInvoiceEntry.RequestWriteAsText(RequestText,TEXTENCODING::UTF8);
      eInvoiceEntry.ResponseWriteAsText(Json,TEXTENCODING::UTF8);
      eInvoiceEntry."Created By" := USERID;
      eInvoiceEntry."Created Date Time" := CURRENTDATETIME;
      eInvoiceEntryMODIFY;
    END ELSE BEGIN 
                   FileName := DELCHR(FileName,'=','/');
                     ServerFile := FileManagement.ServerTempFileName('.json');
                     IF FILE.EXISTS(ServerFile) THEN
                       ERASE(ServerFile);
                    TempFile.CREATE(ServerFile);
                    TempFile.CREATEOUTSTREAM(OutStrm);
                    OutStrm.WRITETEXT(DN_JSonConvert.Parse(StringBuilder.ToString).ToString);
                    TempFile.CLOSE;
                    LocalFile := FileManagement.SaveFileDialog('Select Folder to Save Json',FileName + '.Json','*.JSON|*.json');
                    IF LocalFile <> '' THEN
FileManagement.DownloadToFile(ServerFile,LocalFile); 
    END;
END;

Note: This code might not run directly, you need to change/update accordingly. Codeunit: Http Web Request Mgt., JSON Management, & File Management are sufficient to call API & easily parse response using few supporting .net variables.

Step 5: Similarly need to write code for cancel IRN. Give a button at e-Invoice Entries page.

Step 6: Finalize your solution by putting required validations to avoid errors. Check the link for validation. 

Happy to help you, pleas comment & give feedback. Or, you may contact us for further detailed information. 

Thanks for reading...


Tuesday, November 24, 2020

Business Central - Automation APIs

Business Central provides automation APIs which can be used to create a new company on the tenant, running RapidStart packages, installing extensions, adding users to user groups and assigning permission sets to users.

Delegated admin credentials and Dynamics 365 Business Central users with permissions, can call the APIs.

For delegated admin access, you must add the Azure Active Directory (Azure AD) application to the AdminAgents group. If the Azure AD application is not added, the consent flow will show an error such as Need pre-consent. For more information, see Pre-consent your app for all your customers in the Graph documentation.

Automation APIs are placed in the microsoft/automation API namespace. In all the examples below, parameters are marked in parenthesis {}. Make sure that only valid parameters are passed.

Create a Company

To create a company, an automationCompany endpoint is available. To create a Company issue a POST request as shown in the following example.

POST https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({companyId})/automationCompanies
Authorization: Bearer {token}

Content-type: application/json
{
    "name": "CRONUS India",
    "displayName": "CRONUS India Ltd.",
    "businessProfileId": ""
}

The {companyId} must be the ID of an valid company on the tenant. Issue a GET automationCompany request to fetch existing companies. 

For Example: Retrieves the properties and relationships of an automationCompany object for Dynamics 365 Business Central.

Http Request: 

GET /microsoft/automation/{apiVersion}/companies({{companyid}})/automationCompanies
Header: Authorization
Value: Bearer {token}

Http Response:

If successful, this method returns a 200 OK response code and list of automationCompany objects in the response body. For example:

{
    "id": "3496bbf8-fcae-4e48-a4f8-cb17c27de0b3",
    "name": "CRONUS India",
    "evaluationCompany": true,
    "displayName": "CRONUS India Ltd.",
    "businessProfileId": ""
}

Note: The company which is created will not be initialized.

To rename a company, issue a PATCH automationCompanies.

Upload and apply a RapidStart package

RapidStart is uploaded, installed, and applied using the APIs described below. RapidStart operations can be time consuming. To get the current status of the RapidStart packages and running operations issue a GET configurationPackages as shown in the following example.

GET https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({companyId})/configurationPackages
Authorization: Bearer {token}

In the response, status for the import and apply status will be shown, as well as information about the RapidStart package.

Insert RapidStart

First step is to create the configuration package, by issuing a POST configurationPackages in the Dynamics 365 Business Central tenant. Once the configuration package is created, the RapidStart package can be uploaded. See the example below.

POST https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({companyId})/configurationPackages

Authorization: Bearer {token}
Content-type: application/json
{
    "code":"{SAMPLE}",
    "packageName": "{SAMPLE}"
}


Upload RapidStart package

Once the configuration package is created, a RapidStart package can be uploaded with a PATCH configurationPackages. See the example below.

PATCH https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({{companyId}})/configurationPackages('{SAMPLE}')/file('{SAMPLE}')/content

Authorization: Bearer {token}
Content-type: application/octet-stream
If-Match: *
Body: RapidStart file.


Import and apply RapidStart package

Once uploaded, the RapidStart package needs to be imported by issuing a POST on the bound action Microsoft.NAV.import.

POST https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({{companyId}})/configurationPackages('SAMPLE}')/Microsoft.NAV.import

Authorization: Bearer {token}

When the RapidStart package is imported it can applied with a POST on bound action Microsoft.NAV.apply.

POST https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({companyId})/configurationPackages('SAMPLE}')/Microsoft.NAV.apply

Authorization: Bearer {token}


Managing users, user groups, and permission sets

The automation APIs enable users to be set up in Dynamics 365 Business Central.

Modifying user properties

Get the current user properties by issuing a GET users. This will get the UserSecurityId needed on subsequent requests.

To modify the user, create a PATCH user request as shown in the example below.

PATCH https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/v1.0/companies({id})/users({userSecurityId})
Content-type: application/json
If-Match:*
{
    "state": "Enabled",
    "expiryDate": "2025-10-01T00:10:59.999Z"
}


Assign user permissions and user groups

To assign users to a user group, issue a POST request against the userGroupMembers entity. See the example below.

POST https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({companyId})/users({userSecurityId})/userGroupMembers

Authorization: Bearer {token}
{ 
    "code": "D365 EXT. ACCOUNTANT",
    "companyName" :"CRONUS Inida"
}

To retrieve the list of user groups issue a GET userGroups. This will return the information that you need for the payload above.

Assigning permission sets is identical to adding users to user groups. GET permissionSet returns information about the available permission sets. To assign a permissionSet issue a POST userPermission as shown in the following example.

POST https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({companyId})/users({userSecurityId})/userPermissions

Authorization: Bearer {token}
{ 
    "id": "SECURITY"
}

Removing the permissionSet from the user is done by issuing a DELETE userPermissions on the users entity.

Handling tenant extensions

Add-on extensions which are already published to the tenant can be installed and uninstalled. Per-tenant extensions can be uploaded and installed. To get the list of all extensions on the tenant, issue a GET extensions. This will return the packageId needed for installing and uninstalling extensions.

Installing and uninstalling published add-on extensions

There are two bound actions available on the extensions endpoint: Microsoft.NAV.install and Microsoft.NAV.uninstall.

Issue a POST extension using the bound actions. See the example below.

POST https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/{apiVersion}/companies({companyId})/extensions({packageId})/Microsoft.NAV.install

Authorization: Bearer {token}


Upload and install a per-tenant extension

Issue a PATCH against the extensionUpload endpoint to upload and install the extension.

Note: Installing per-tenant extensions using Automation APIs is only possible in SaaS.

Uninstalling the extension can be done through the bound action Microsoft.NAV.uninstall, as with the add-on extensions.

Monitoring extension installation progress

To view ongoing extension installation status, issue GET extensionDeploymentStatus as shown in the following example.

GET https://api.businesscentral.dynamics.com/v2.0/{environment name}/api/microsoft/automation/v1.0/companies({companyId})/extensionDeploymentStatus


Blog Source: Microsoft Docs

Sunday, June 28, 2020

Business Central Integration with Rest API – Deep Drive – COVID-19 India Tracker (Part 1)

Dear Friend, I am back with some useful stuff for you. Hope this may help you to deep drive with API Integration. While thinking to work on large data for Power BI analysis report, I got the details about “https://www.covid19india.org/” website from my colleague Mr. Anil Pandey . Where we decided to get the JSON data in Power BI to create same dashboard.
While checking website I got the details of various API details by calling those we can get variety of data on COVID-19 India cases. My previous posts viewed by lots of readers and this inspired me to develop this in Business Central for learning purpose and share with you all. I can’t say, have done this as a big solution. But try to give a overall feel of creating an APP. I know there are lots of Dynamics Lancers who can do these very quickly & better way. My purpose only to help those who still thinking that integration is a such complex task.
I haven’t used all available API at https://www.covid19india.org/. Only more thing I need to mentioned here, data are not realtime. It is a day before.
To work with this integration, I have included development like:
  • Role Centre Page including Navigation menus, Action bar, Headline, Chart & CardPart or ListPart page.
  • Tables
  • Pages
  • Codeunits
  • Charts
  • Reports
  • Translations (Something unusual using Hindi)

In this part, I will only talk about the look and feel of development & functional aspect of the story. Technical details I will share in subsequent part to this blog series. Hope my initiative will inspire you before I release the next part for technical details. Please give a try, its quite easy and interesting to work on such integration development.
Below is image of Role Centre Page:

Continue reading, click here...

Thursday, June 25, 2020

Business Central Integration with Rest API – Part 3 (OnPrem & SaaS)

Dear Reader’s, I am sharing simple REST API integration with Business Central 2020 Wave 1 release. In previous Part-1 & Part-2, I have demonstrated GET method of API. In this Part, I will explain POST method, where a data request & response will be handled. I want to thank the creator of API and available for us to check & learn the POST method (Request & Response handling).

Below sample will run on both OnPrem & SaaS as well. In the following example we will call an API request to Create resource by supplying Name & Job details. And in response API will return Id & Created At along with the request info Name & Job.

API URL: https://reqres.in/api/users

Sample Request: { “name”: “Your Name”, “job”: “Your Job Name” }

Response: {“name”:”Your Name”,”job”:”Your Job Name”,”id”:”Numeric”,”createdAt”:”DateTime in YYYY-MM-DDTHH:MM:SS.sssZ”}

Click hear to read more

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…