Tuesday 17 October 2023

Calling APIs from D365 Using Content Type Text "application/x-www-form-urlencoded" POST request

 

In the world of enterprise resource planning (ERP), Microsoft Dynamics 365 (D365) stands out as a powerful and versatile solution. To unlock the full potential of D365, you often need to integrate it with other systems or automate certain processes. One common way to achieve this is by calling D365 APIs. In this blog post, we'll walk you through the process of calling D365 APIs using the "application/x-www-form-urlencoded" content type.

Understanding the "application/x-www-form-urlencoded" Content Type

Before we dive into calling D365 APIs, let's first understand what the "application/x-www-form-urlencoded" content type is. This content type is commonly used for sending data to web servers, especially when dealing with HTML forms. It represents key-value pairs in the URL-encoded format, where data is sent as a series of name-value pairs separated by the '&' character.

Prerequisites

To start calling D365 APIs, you'll need the following prerequisites:

1. Microsoft Dynamics 365 Account: You should have access to a D365 instance and the required permissions to call APIs.

2. API Endpoint: You should know the API endpoint you want to call. Consult D365's API documentation to find the specific endpoint URL.

3. API Key or Authentication Token: Depending on your D365 instance's security settings, you might need an API key or an authentication token.

Calling D365 APIs with "application/x-www-form-urlencoded" Content Type

Now, let's walk through the steps to call a D365 API using the "application/x-www-form-urlencoded" content type:

Step 1: Assemble Your Data

Prepare the data you want to send in the request in the "application/x-www-form-urlencoded" format. This means you need to create a string that contains key-value pairs separated by '&' and encode them properly.

Step 2: Set Up Your HTTP Request below is the sample code 

using Newtonsoft.Json.Linq;

using Newtonsoft.Json.JsonSerializer;

using System.Text.Json;

using System.IO.FileAccess;

using System.IO.Directory;

using System.IO;

using Newtonsoft.Json.Linq.JObject;

using System.Net.Http.HttpClient;

using System.Net.Http.HttpRequestMessage ;

using System.Net.Http.HttpResponseMessage;

internal final class AuthenticationRunnableClass

{

    /// <summary>

    /// Class entry point. The system will call this method when a designated menu 

    /// is selected or when execution starts and this class is set as the startup class.

    /// </summary>

    /// <param name = "_args">The specified arguments.</param>

    public static void main(Args _args)

    {

        System.Net.Http.HttpClient clientlocal;

        System.Net.Http.HttpRequestMessage requestlocal;

        System.Net.Http.HttpResponseMessage responselocal;

        System.Text.Encoding encoding;

        try

        {

            // Create an instance of the HttpClient

            clientlocal = new System.Net.Http.HttpClient();

            // Define the request URL

            str requestUrl = 'https://your-d365-api-endpoint.com';

    // Create the content in application/x-www-form-urlencoded format

            str formData = 'client_id=xx-xxxx&client_secret=xxxxx&grant_type=client_credentials&scope=alf.scope.integration.api&acr_values=tenant:xxxx'; // Replace with your form data //This is the text which is used to send with URL

            encoding = System.Text.Encoding::UTF8;

            // Create the content as StringContent

            System.Net.Http.StringContent content = new System.Net.Http.StringContent(formData, encoding, 'application/x-www-form-urlencoded');

            // Send the POST request with the form data

            responselocal = clientlocal.postAsync(requestUrl, content).Result;

            // Handle the response as needed

            int statusCode = any2Int(responselocal.get_StatusCode());

            str responseContent = responselocal.get_Content().readAsStringAsync().Result;

            // Handle the response data and potential errors

            if (statusCode == 200)

            {

                // Request was successful; process the response content

                info(responseContent);

            }

            else

            {

                // Handle the response based on the status code (e.g., log an error)

                error("HTTP request failed with status code: " + int2str(statusCode));

            }

        }

        catch (Exception::Error)

        {

            // Handle exceptions that may occur during the request

            error("An error occurred during the HTTP request.");

        }

    }

}

Step 3: Handle the Response

Once you send the request, you can handle the response from the D365 API. Be sure to check the status code and parse the response data accordingly. The code below show how to handle the response 

// Handle the response data and potential errors

            if (statusCode == 200)

            {

                // Request was successful; process the response content

                info(responseContent);

            }

            else

            {

                // Handle the response based on the status code (e.g., log an error)

                error("HTTP request failed with status code: " + int2str(statusCode));

            }


Conclusion

Calling D365 APIs using the "application/x-www-form-urlencoded" content type is a common way to integrate D365 with other systems or automate processes. Understanding the format and following the steps outlined in this blog post can help you make successful API requests and leverage the full power of Microsoft Dynamics 365. Make sure to refer to D365's API documentation for the specific endpoints and data you need to interact with in your integration projects.






No comments:

Update NuGet package to new MS D365FO version

1. Import the NuGet package files from LCS for that particular version please take the PU version files only. a. Goto LCS-->Asset Libra...