web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Unanswered

Pull API json data into D365 F and O

(1) ShareShare
ReportReport
Posted on by 58
Hi,
I am new to D365 F&O. Could you please guide me on the task below?
 
Q: How to pull API json data into D365 F and O tables?
 
Code:
 
class GetAPIClient
{
    public static str callExternalAPI(str url)
    {
        System.Net.Http.HttpClient httpClient;
        System.Net.Http.HttpResponseMessage responseMessage;
        str responseData;
        // Initialize the HttpClient
        httpClient = new System.Net.Http.HttpClient();
        
        // Set a timeout for the HTTP client (e.g., 30 seconds)
        httpClient.Timeout = new System.TimeSpan(0, 0, 30);
        try
        {
            // Send the GET request
            responseMessage = httpClient.GetAsync(url).Result;
            // Ensure the request was successful
            responseMessage.EnsureSuccessStatusCode();
            // Read the response content
            responseData = responseMessage.Content.ReadAsStringAsync().Result;
        }
        catch (Exception::CLRError)
        {
            // Handle any errors that occur during the request
            ClrObject clrEx = ClrInterop::getLastException();
            error(strFmt("API call failed: %1", clrEx.ToString()));
            // Log additional details
            error(strFmt("Exception Type: %1", clrEx.GetType().ToString()));
            error(strFmt("Exception Message: %1", clrEx.Message()));
            throw error(strFmt("API call failed with exception: %1 - %2", clrEx.GetType().ToString(), clrEx.Message()));
        }
        finally
        {
            // Dispose of the HttpClient
            httpClient.Dispose();
        }
        return responseData;
    }
    public static void main(Args _args)
    {
        try
        {
            str result = GetAPIClient::callExternalAPI("https://api.restful-api.dev/objects/7");
            info("API Response: " + result);
            // Parse the JSON response using CLRInterop
            System.Type jObjectType = CLRInterop::getType("Newtonsoft.Json.Linq.JObject");
            System.Object jObject = jObjectType.getMethod("Parse").Invoke(null, [result]);
            info("Parsed JSON successfully.");
            // Extract the 'name' property
            str name = CLRInterop::getAnyTypeForObject(jObjectType.getMethod("get_Item").Invoke(jObject, ["name"])).ToString();
            info("Name: " + name);
            // Extract 'data' object
            System.Object dataObject = jObjectType.getMethod("get_Item").Invoke(jObject, ["data"]);
            info("Data object extracted.");
            // Extract individual properties from 'data'
            int year = CLRInterop::getAnyTypeForObject(dataObject.GetType().getMethod("get_Item").Invoke(dataObject, ["year"]));
            real price = CLRInterop::getAnyTypeForObject(dataObject.GetType().getMethod("get_Item").Invoke(dataObject, ["price"]));
            str cpuModel = CLRInterop::getAnyTypeForObject(dataObject.GetType().getMethod("get_Item").Invoke(dataObject, ["CPU model"])).ToString();
            str hardDiskSize = CLRInterop::getAnyTypeForObject(dataObject.GetType().getMethod("get_Item").Invoke(dataObject, ["Hard disk size"])).ToString();
            info(strFmt("Year: %1, Price: %2, CPU Model: %3, Hard Disk Size: %4", year, price, cpuModel, hardDiskSize));
           
            APIData apiData;
          //  ttsBegin;
            apiData.clear();
            apiData.Name = name;
            apiData.Year = year;
            apiData.Price = price;
            apiData.CpuModel = cpuModel;
            apiData.HardDiskSize = hardDiskSize;
            apiData.insert();
           // ttsCommit;
            info("Data inserted successfully.");
        }
        catch (Exception::CLRError)
        {
            ClrObject clrEx = ClrInterop::getLastException();
            error(strFmt("API call failed in main method: %1", clrEx.ToString()));
        }
    }
}
I have the same question (0)
  • Martin Dráb Profile Picture
    235,979 Most Valuable Professional on at
    Pull API json data into D365 F and O
    Moved from Dynamics AX forum.
     
    What is your question? You showed some code without explaining what you want to discuss with us.
     
    By the way, there are many things you can improve in your code.
     
    This looks extremely overcomplicated to me:
     
    CLRInterop::getAnyTypeForObject(jObjectType.getMethod("get_Item").Invoke(jObject, ["name"])).ToString();
     
    Why can't you call jObject.get_Item('name') directly?
     
    By the way, consider deserializing JSON to a contract object rather then interpretting a JObject is code.
     
    Don't use ClrInterop::getLastException(). F&O has an easier way to get the exception:
    System.Exception ex;
    try
    {
        ...
    }
    catch (ex)
    {
        ...
    }
    The call of apiData.clear() has no effect and can be thrown away.
     
    You can simplify your code by utilizing the 'using' statement in both contexts (to replace try/finally) and to avoid fully-qualified names of .NET classes.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Andrés Arias – Community Spotlight

We are honored to recognize Andrés Arias as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Sohaib Cheema Profile Picture

Sohaib Cheema 882 User Group Leader

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 723 Super User 2025 Season 2

#3
CA Neeraj Kumar Profile Picture

CA Neeraj Kumar 518

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans