To start with development to consume webAPI using X++ in D365 finance and operation, make sure you are adding “Retail” package as reference in your model.
Here you have three important classes to consider in your code.
RetailWebRequest : Generates a web request by initialsing the required parameters.
RetailCommonWebAPI : class is the class grouping several over-the-web communication,methods like sending an HTTP POST or GET requests and transforming the response to X++ data structures.
RetailWebResponse : Generates a web response by initialsing the required parameters.
First step is start with creating WebRequest.
Sample code
private RetailWebRequest getRequest()
{
url = strLTrim(@'https://apidev.KARTIKHANSORG.com/d365/v1/customer-balances?AccountNum=100&Group=Retail&location=10&country=US');
str header = strFmt('Ocp-Apim-Subscription-Key: %1',keyValue);
str method = 'GET';
str contentType = @'application/json';
RetailWebRequest webRequest = RetailWebRequest::newUrl(url);
webRequest.parmMethod(method);
webRequest.parmHeader(header);
webRequest.parmContentType(contentType);
return webRequest;
}
second step is creating web request and get response.
RetailWebRequest webRequest = this.getRequest();
RetailCommonWebAPI webApi = RetailCommonWebAPI::construct();
RetailWebResponse webResponse = webApi.getResponse(webRequest);
str responseData = webResponse.parmData();
Last but most importantly parse response and fetch data.
if (webResponse.parmHttpStatus() == 200)
{
Map responseMap = RetailCommonWebAPI::getMapFromJsonString(responseData);
MapEnumerator mapEnumerator;
mapEnumerator = responseMap.getEnumerator();
while (mapEnumerator.moveNext())
{
info(strFmt(" domain value %1 %2",mapEnumerator.currentKey(),mapEnumerator.currentValue()));
}
//
}
}
Sample exception handling code for Web api call
try
{
Amount = this.callAPI();
}
catch (Exception::CLRError)
{
error("error");
System.Exception ex = ClrInterop::getLastException();
if (ex != null)
{
ex = ex.get_InnerException();
if (ex != null)
{
error(ex.ToString());
}
}
}
catch
{
throw error("Error");
}
Leave a comment