Restful APIs are some of the most heavily used APIs in industry. They have become a good alternative for SOAP, COBRA and RPC. In this post we’ll look at the steps for consuming REST based APIs in Dynamics AX.
Dynamics AX provides great support for interacting with REST based APIs. We have a simple routine with which we can call different REST based APIs.Dynamics AX uses the System.Net namespace to call external APIs. The classes that are used to call the services are HttpWebRequest and HttpWebResponse.
Let’s look at a sample in which we’ll call a REST API with the HTTP GET Method
Declaration:
The following are the classes that will be used to get the data
System.Net.HttpWebRequestwebReq;
System.Net.HttpWebResponsewebRes;
CLRObjectclrObj;
System.IO.Stream stream;
System.IO.StreamReaderstreamRead;
System.IO.StreamWriterstreamWrite;
System.Net.ServicePointservicePt;
System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();
Processing Of API Call
Now let’s jump to the code that will get the data from a REST based API.
//This line gives the user control to run unmanaged and managed code
newInteropPermission(InteropKind::ClrInterop).assert();
// Create Object for adding headers
headers = new System.Net.WebHeaderCollection();
clrObj = System.Net.WebRequest::Create(‘https://test.com/rest_services/v1/endpoint’);
webReq = clrObj;
//Set Method Type
webReq.set_Method(“GET”);
webReq.set_KeepAlive(true);
// Set Content type
webReq.set_ContentType(“application/xml”);
// Add Authorization code
headers.Add(“Authorization”, “sdfgvczzxcbtyfrvb”);
//Add header to request
webReq.set_Headers(headers);
//Get Service Point
servicePt = webReq.get_ServicePoint();
servicePt.set_Expect100Continue(false);
//Gets the response object
webRes = webReq.GetResponse();
//Get Stream
stream = webRes.GetResponseStream();
streamRead = new System.IO.StreamReader(stream);
stream.Close();
webRes.Close();
With the help of this code we can easily get the data stream from an external API. In m next post we’ll discuss the POST and PUT methods we can use for this.
ABOUT Folio3 Dynamics Services
As Dynamics AX experts we specialize in Dynamics AX development including Dynamics AX customization, integration, implementation and mobility solutions. If you have a Dynamics AX development requirement you would like to discuss or would like to know more about our Dynamics AX development services, please get in touch with us.