How to call a web API from Dynamics 365 FO X++

A short example how to autenticate and talk to web based API from x++

The code below is divided into two pieces/methods just to ease how to do things. One that authenticates to an API and the other one takes the authentication token and adds it to the call. The examples below maybe don’t fit your scenario due to all API are different but the procedure is almost the same.

void authentication() 
{
str                rawResponse;
Map                responseData;
RetailWebResponse  response;
;
//URL to the API, Data, Header data, ContentType: 'application/x-www-form-urlencoded'
response = webApi.makePostRequest([URL], @'grant_type=client_credentials&client_id=[clientId]', [Header], [ContentType]);
if(response.parmHttpStatus() != 200)
throw error("Couldnt authenticate");

rawResponse = response.parmData();
responseData = RetailCommonWebAPI::getMapFromJsonString(rawResponse);
token = responseData.lookup("access_token");
}

In this example below, we got our response back as an ARRAY. we remove the ARRAY tags and with that, the call is translated into JSON.

private void call()
{
RetailWebRequest   webRequest;
RetailWebResponse  response;
str                rawResponse, ref;
Map                responseData;
;

webApi = RetailCommonWebAPI::construct();

//URL to get data
webRequest = RetailWebRequest::newUrl([URL]);
//Send token through JSON GET call
webRequest.parmHeader(@'Authorization: Bearer '+token);
webRequest.parmContentType("application/json");
webRequest.parmMethod("GET");

response = webApi.getResponse(webRequest);

if(response.parmHttpStatus() != 200)
throw error("No data is returned");
rawResponse = substr(response.parmData(),2,(strlen(response.parmData())-2));
responseData = RetailCommonWebAPI::getMapFromJsonString(rawResponse);

ref        = responseData.lookup("ref");
}

Leave a Reply

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