hljs.configure({cssSelector: "code"}); hljs.highlightAll();

Friday, May 26, 2023

X++ code to consume API in D365FO

We can consume the API's by using System.Net.HttpWebRequest  and System.Net.WebHeaderCollection.

Find below sample code to call API.
    public void callAPI(str   _requestJson,str _url)
    {
        System.Net.HttpWebRequest       request;
        System.Net.HttpWebResponse      response;
        CLRObject                       clrObj;
        System.Exception                ex;
        System.Net.WebHeaderCollection  httpHeader;
        System.IO.Stream                requestStream, responseStream;
        System.IO.StreamWriter          streamWriter;
        RefRecId                        refrecid = 0;
	    System.Byte[]                   bytes        = null;
        System.Text.Encoding            encoding     = null;
        str  token;
        try
        {
            httpHeader = new System.Net.WebHeaderCollection();
            new InteropPermission(InteropKind::ClrInterop).assert();         
            clrObj = System.Net.WebRequest::Create(_url);

            request = clrObj;

	    // API Authentication. It can vary for different API providers
            httpHeader.Add("accessToken", token);
          
            request.set_Headers(httpHeader);
            request.Method = "POST";
            request.ContentType = "application/json";

            requestStream = request.GetRequestStream();
			
            streamWriter = new System.IO.StreamWriter(request.GetRequestStream());
	    streamWriter.Write(_requestJson); // writing JSON
            streamWriter.Flush();
            streamWriter.Close();

	    /*
	    if(_requestJson)
            {
                // info(_requestJson);
                encoding    = System.Text.Encoding::ASCII;//get_UTF8();
                bytes       = encoding.GetBytes(_requestJson);
                httpRequest.set_ContentLength(bytes.get_Length());
                stream      = httpRequest.GetRequestStream();
                stream.Write(bytes,0,bytes.get_Length());
                stream.Close ();
                
            }*\
			
            response = request.GetResponse();
            System.IO.StreamReader streamRead = new System.IO.StreamReader(response.GetResponseStream());
            str res = streamRead.ReadToEnd().ToString();
            info(res);                  
        }
        catch
        {
            //exception
            ex = CLRInterop::getLastException().GetBaseException();
            error(ex.get_Message());
        }
    }

No comments:

Post a Comment