D365 FO: Consume & Call Restful API using X++, pass request header & Post JSON message in body


CONSUME & CALL RESTFUL API USING X++, PASS REQUEST HEADER & POST JSON MESSAGE IN BODY – Client shared some REST APIs and REST web-services. The web-service or REST API needs to be consumed in Microsoft Dynamics 365 finance & operations using X++. The HttpWebRequest contains request headers i.e WebHeaderCollection which needs to be filled in API header. The content type is application/json. The request body input should be a valid JSON format and POST method of REST API will be called .HttpWebResponse will be received & deserialized in Microsoft Dynamics 365 fin & ops


HttpWebResponse, HttpWebRequest & WebHeaderCollection

Sample Code

System.Net.HttpWebRequest       request;
        System.Net.HttpWebResponse      response;
        CLRObject   clrObj;
        System.Exception        ex;
        System.Net.WebHeaderCollection httpHeader;
        System.IO.Stream        requestStream, responseStream;
        Table1  table1;
        System.IO.StreamWriter  streamWriter;
            select firstonly1 crosscompany table1;
            httpHeader = new System.Net.WebHeaderCollection();
            new InteropPermission(InteropKind::ClrInterop).assert();
            clrObj = System.Net.WebRequest::Create("https:XXXXX");
            request = clrObj;
	    // adding headers
            httpHeader.Add("Schema-Type", "XXXXX");
            httpHeader.Add("owner_id", "XXXXX");
            httpHeader.Add("gstin", "XXXXX");
            request.Method = "POST";
            request.ContentType = "application/json";
            requestStream = request.GetRequestStream();
            streamWriter = new System.IO.StreamWriter(request.GetRequestStream());
            streamWriter.Write(table1.FieldString1); // writing JSON
            response = request.GetResponse();
            System.IO.StreamReader streamRead = new System.IO.StreamReader(response.GetResponseStream());
            ex = CLRInterop::getLastException().GetBaseException();

One thought on “D365 FO: Consume & Call Restful API using X++, pass request header & Post JSON message in body”

Leave a Reply