Monday, April 6, 2015

Calling RESTful services using AX 2009, AX 2012


While integrating Dynamics AX with other systems, you 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 2 systems. The Job written below is the example of how one can call REST service from within AX.

Tip: Either you want to push data from AX or pull data in AX, you can always use POST method. In case you want to send data out of AX, you will always need to use POST method with your data as shown below in postData variable. In case, you need to download data in AX from some other system, you can still use POST method and send your credentials, API key for authentication purpose and download your data either in XML or JSON format as I have done in returnValue variable in job written below.

static void Job1(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('api_key=%1&account_id=%2', "DEC8A896-9244-4FAB-ACB9-15B932E630CB", "3");

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

    url = "http://yoururl.com/services/api/external/authentication.ashx?login";

    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();


}