Skip to main content

Notifications

Dynamics 365 Community / Forums / Finance forum / Pull API json data int...
Finance forum
Unanswered

Pull API json data into D365 F and O

Posted on by 8
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()));
        }
    }
}
Categories:
  • Martin Dráb Profile Picture
    Martin Dráb 227,996 Super User 2024 Season 2 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.

Helpful resources

Quick Links

Dynamics 365 Community Update – Sep 9th

Welcome to the next edition of the Community Platform Update. This is a weekly…

Dynamics 365 Community Newsletter - August 2024

Catch up on the latest D365 Community news

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 290,186 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 227,996 Super User 2024 Season 2

#3
nmaenpaa Profile Picture

nmaenpaa 101,148

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans