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
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
We create a POST request and set the content type to "application/json".
3. Handling the Response
The response stream is read as a plain string. Then we deserialize it into a Map using:
This allows us to extract specific fields, such as:
Comments
Post a Comment