Pages

Monday, 19 October 2015

RestFul API Services in dynamics AX2009 & AX2012

When we integrating Dynamics AX with other systems, we might need to call REST services in Dynamics AX to Pull data in AX (or) Push data out of AX to other systems.
REST services are the easiest and very useful way to provide the interface between two systems. 
Here you go the job written below is the example of how we can call REST service from within AX.

static void AccessingAPI(Args _args)
{
    str                                                   url;
    str                                                   postData;
    str                                                   returnValue;
    System.Net.HttpWebRequest       request;
    System.Net.HttpWebResponse    response;
    System.Byte[]                                byteArray;
    System.IO.Stream                    dataStream;
    System.IO.StreamReader          streamReader;
    System.Net.ServicePoint         servicePoint;
    System.Net.ServicePointManager  servicePointManager;
    CLRObject                       clrObj;
    System.Text.Encoding            utf8;

    ;

    postData = strfmt('First_Name=%1&Id=%2', "DaxCustomer", "DAX-00001");

    new InteropPermission(InteropKind::ClrInterop).assert();

    url ="http://yoururl.com/api/services/add?app_id=''&app_key=''&token=''&secret=''&format=xml";

    clrObj = System.Net.WebRequest::Create(url);
    System.Net.ServicePointManager::set_Expect100Continue(false); 

    request = clrObj;
    request.set_Method("POST");
    utf8 = System.Text.Encoding::get_UTF8();
    byteArray = utf8.GetBytes(postData);
    request.set_ContentType("application/x-www-form-urlencoded");
    request.set_ContentLength(byteArray.get_Length());

    dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.get_Length());
    dataStream.Close();

    try
    {
        response = request.GetResponse();
    }
    catch (Exception::CLRError)
    {
    postdata = "";
    }

    dataStream = response.GetResponseStream();
    streamReader = new System.IO.StreamReader(dataStream);
    returnValue = streamReader.ReadToEnd();

    info(returnvalue);

    streamReader.Close();
    dataStream.Close();
    response.Close(); 


}

3 comments:

  1. Hi Saravana,
    Hope you are doing well!

    I have a requirement to consume restful service in ax 2009. for that, i have followed your code when i use your code. I am getting an error. "CLRObject object not initialized. Stack trace (C)\Jobs\AccessingAPI - line 47". could you please help here

    ReplyDelete
  2. Vignesh, any luck with this?

    ReplyDelete