JSON-Based HTTP POST Request from X++ to Retrieve an Access Token

In today's connected systems, integrations between Dynamics AX and external APIs are essential. One common scenario is retrieving an access token from a remote API for authentication. In this post, I'll show you how to make a POST request with JSON from X++ and handle the response.

We'll walk through a complete example where we send credentials to an API and parse the response to retrieve an access token.

Prerequisites

To follow along, you should have:

  • Basic familiarity with X++

  • Access to System.Net and System.IO namespaces via CLR Interop

  • A configured HRMParameters table to store credentials


X++ code:

System.Net.HttpWebRequest                 request;
System.Net.HttpWebResponse              response;
System.IO.StreamWriter                       streamWriter;
System.IO.StreamReader                      streamReader;
System.IO.Stream                                  responseStream;
System.Exception                                  ex;
CLRObject                                            clrObj;
str                                                          jsonBody, responseData;
ResponseTokenData                             tokenResponse = new ResponseTokenData();
HRMParameters                                   hrmParameters = HRMParameters::find();
Map                                                       mapRoot;
str                                                          myToken;

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

try
{
    // Prepare JSON body
    jsonBody = strFmt(@'{
        "email": "%1",
        "password": "%2",
        "Token": "%3"
    }',
    hrmParameters.TokenRequestEmail,
    hrmParameters.TokenRequestPassword,
    hrmParameters.Token);

    // Create HTTP request
    clrObj = System.Net.WebRequest::Create("<API_URL>");
    request = clrObj;
    request.Method = "POST";
    request.ContentType = "application/json";
    request.Accept = "application/json";
    request.get_Headers().Add("Accept-Encoding", "identity"); // Ask for plain response

    // Write request body
    streamWriter = new System.IO.StreamWriter(request.GetRequestStream());
    streamWriter.Write(jsonBody);
    streamWriter.Flush();
    streamWriter.Close();

    // Send request and get response
    response = request.GetResponse();
    responseStream = response.GetResponseStream();

    // Read and convert response
    streamReader = new System.IO.StreamReader(responseStream);
    responseData = streamReader.ReadToEnd();

    // Parse JSON response
    mapRoot = FormJsonSerializer::deserializeObject(responseData);
    myToken = mapRoot.get("access_token");

    info(strFmt("Access token retrieved: %1", myToken));
}
catch (Exception::CLRError)
{
    ex = CLRInterop::getLastException();
    error(ex.ToString());
}

Key Components Explained

1. JSON Body Construction

jsonBody = strFmt(@'{ "email": "%1", "password": "%2", "Token": "%3" }', ...);

We dynamically create a JSON string using values stored in the HRMParameters table. This string becomes the payload of the POST request.

2. Creating and Sending the Request

clrObj = System.Net.WebRequest::Create("<API_URL>"); request = clrObj; request.Method = "POST"; request.ContentType = "application/json";

We create a POST request and set the content type to "application/json".

3. Handling the Response

streamReader = new System.IO.StreamReader(responseStream); responseData = streamReader.ReadToEnd();

The response stream is read as a plain string. Then we deserialize it into a Map using:

mapRoot = FormJsonSerializer::deserializeObject(responseData);

This allows us to extract specific fields, such as:

myToken = mapRoot.get("access_token");

4. Error Handling

If the request fails (e.g., due to a timeout or invalid credentials), the catch block catches the CLR exception:

ex = CLRInterop::getLastException(); error(ex.ToString());

This ensures we get meaningful debugging information.

Conclusion

This approach is a practical way to integrate external APIs with Dynamics AX via CLR Interop, and the pattern is reusable for most JSON-based API interactions.

Whether you're fetching access tokens, pushing data, or querying external services, this gives you a solid starting point.

Comments

Popular posts from this blog

Calling an External API from D365FO Using X++ to Retrieve a Token

Restricting Date Selection in Dynamics 365 FO using X++