AX 2012, Calling Webservice, Development, Rest APIs, Uncategorized

Calling Rest API from AX 2012

AX 2012 supports system.Net namespace interface. This interface provides simple programming interface for many of the protocols used on the networks today. Herewith i am sharing a simple example to call a rest API asynchronously.  it is very lightweight and has hardly an impact if you are calling asynchronously.

 

static void CallRestAPISample(Args _args)
{
 System.Net.WebHeaderCollection headers ;
 System.Net.WebClient webclient;
 System.Uri uri;
 
 // Create XML msg or string message as parameter to call the Rest API. 
 str msgstring = '<?xml version="1.0"?> ';
 
 msgstring += '<LogRequest>' ;
 
 msgstring += '<ApplicationName>AX Error Tracking</ApplicationName>';
 msgstring += ' <Date>06-22-2017 12:58:22 PM</Date>';
 msgstring += '<ThreadID>0</ThreadID>';
 msgstring += '<LogLevel> <INFO>false</INFO> <DEBUG>false</DEBUG> <ERROR>true</ERROR> <FATAL>false</FATAL> <WARN>false</WARN> </LogLevel>';
 msgstring += '<LogDetails> <ExceptionMessage>Test Exception</ExceptionMessage> <Message>This is test message from AX Logging Call.</Message> </LogDetails> ';
 msgstring += '<Metadata> <Data> <Name>ENV</Name> <Value>DEV</Value> </Data> <Data> <Name>Server</Name> <Value>AX AOS 1</Value> </Data> <Data> <Name>Source</Name> <Value>DAX</Value> </Data> </Metadata>';
 msgstring += '<Email> <From>FromAddr@Fromserver.com</From> <To>toaddrr@toserver.com</To> <Subject>AX Logging Test</Subject> <Message>This is test message</Message> <HasAttachments>false</HasAttachments> <IsBodyHtml>true</IsBodyHtml> <IncludeLogDetails>true</IncludeLogDetails> </Email>';
 msgstring += '</LogRequest>';
 
 
 info(strFmt("%1",time2str(timeNow(),1,1)));
 // initilizing host URI
 uri = new System.Uri("http://LogginServiceHost/api/Log/LogRequest");// FAKE SERVICE HOST ADDRESS
 // initializing webClient
 webclient = new System.Net.WebClient();
 headers = webclient.get_Headers();
 // Set header content type
 Headers.Add(System.Net.HttpRequestHeader::ContentType, "text/xml;charset=utf-8");
 // call API asynchronously
 webclient.UploadStringAsync(uri,msgstring);
 
 info(strFmt("%1",time2str(timeNow(),1,1)));

}

Standard