API call using X++ in D365 FO

PHOTO EMBED

Mon Sep 02 2024 06:00:12 GMT+0000 (Coordinated Universal Time)

Saved by @Manjunath

System.Net.HttpWebRequest request;
        System.IO.Stream stream;
        System.Exception sysEx;
        
        request = System.Net.WebRequest::Create("URL") as System.Net.HttpWebRequest;
        request.Method = 'POST';
        request.ContentType = 'application/json';

        // Set the request headers
        System.Net.WebHeaderCollection headerCollection = request.Headers;
        headerCollection.Set('Name', 'Value');

        var utf8 = System.Text.Encoding::get_UTF8();


        // Set the request body
        var byteArrayPayload = utf8.GetBytes("{\"key1\":\"value1\",\"key2\":\"value2\"}");
         try
        {
            // send out the payload
            using (System.IO.Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArrayPayload, 0, byteArrayPayload.Length);
            }

            // request.GetResponse() may already result in an error if the request was e.g. a Bad Request(Status Code 400). This should be handled upstream via our global error handling.
            using (System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
            {
                stream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                str responseBody = reader.ReadToEnd();
            }
        }
        catch (sysEx)
        {
            throw;
        }

content_copyCOPY

To make a POST request in X++, you can use the WinHttp class, which is a built-in class in Dynamics 365 Finance and Operations that provides HTTP client functionality. The WinHttp class is part of the System.Net namespace. Here is an example of how to use the WinHttp class to make a POST request: In this example, we create a HttpWebRequest object by calling the Create method on the HttpWebRequest class, passing in the URL of the API endpoint as an argument. We then set the HTTP method to "POST" on the Method property and ContentType as required on the request object. Next, we set the request headers by using the WebHeaderCollection object that we can modify. We then set the request body by calling the GetRequestStream method on the request object, which returns a stream that we can write the request body data to. In this example, we create a JSON object and encode it as a byte array, and then write the byte array to the request stream. Finally, we send the request by calling the GetResponse method on the request object, which returns a HttpWebResponse object that contains the response data. We read the response stream and convert it to a string using a StreamReader object. The resulting responseBody string contains the response data from the API endpoint.

https://dax365.blogspot.com/2023/05/api-call-using-x-in-d365-fo.html?m=1