Skip to main content

Notifications

Announcements

No record found.

Finance | Project Operations, Human Resources, ...
Unanswered

Pull API json data into in x++

Posted on by 2
Hi,
I am new to D365 F&O. Could you please guide me on the task below?
 
Q: How to pull API data into in x++?
 
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()));
        }
    }
}
  • Martin Dráb Profile Picture
    Martin Dráb 230,235 Most Valuable Professional on at
    Pull API json data into in x++
    This is a duplicate. I already replied to an identical question a week ago.

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans