Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

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

How to consume CRM API GET Method in X++

(0) ShareShare
ReportReport
Posted on by 115

I have CRM API with URL & Authentication (Bearer Token) , In Postman App , I successfully get the Response with the GET method.

I need same thing to implement in X , for this I written below code , but Its not working .

static void AXCRMGET(Args _args)
{
        int                                                      find;
        str                                                      url,aosUri,activeDirectoryTenant;
        str                                                      activeDirectoryClientAppId;
        str                                                      activeDirectoryClientAppSecret;
        str                                                      postData,activeDirectoryResource;
        str                                                      aadClientAppSecret,oAuthHeader;
        str                                                      returnValue,jsonString,jsondszstr, byteTokenStr;
        System.Net.HttpWebRequest                                request;
        System.Net.HttpWebResponse                               response;
        System.IO.Stream                                         dataStream;
        System.IO.StreamReader                                   streamRead;
        System.IO.StreamWriter                                   streamWrite;
        System.Net.ServicePoint                                  servicePoint;
        System.Net.ServicePointManager                           servicePointmgr;
        System.Net.HttpVersion                                   version;
        CLRObject                                                clrObj;
        Newtonsoft.Json.JsonReader                               reader;
        System.Text.Encoding                                     utf8;
        Counter                                                  countCounter;
        Object                                                   obj;
        Map                                                      data;
        System.Byte[]                                            byteArraynew;
        System.Byte[]                                            byteArray, byteArrayToken;


        System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();

        str  token  = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImpTMVhvMU9XRGpfNTJ2YndHTmd2UU8yVnpNYyIsImtpZCI6ImpTMVhvMU9XRGpfNTJ2YndHTmd2UU8yVnpNYyJ9.eyJhdWQiOiJodHRwczovL2JpYW1wZGV2LmNybS5keW5hbWljcy5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvMzQxYWM1NzItMDY2Yy00NmY2LWJmMDYtYjJkMGM3ZGRmMWJlLyIsImlhdCI6MTY0NzQ5MjA3NiwibmJmIjoxNjQ3NDkyMDc2LCJleHAiOjE2NDc0OTYxNzYsIm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hCCSGQokeRZaj57fD8GU4Yjotobzn6uSQkHa8UCgeo9OiwysLvCJ9souy3w0Oxre_RK59oV2DaN8k13WDZ4TJlaXHdwlFzR1z5ufLzXmYwX5kRVdpnNqi4U-TAmdjnF3WC40lwuVn4GuSggupvwowywEOK3TnBEwUbIdqt2ZEcmaCpoA6KZUoahDVXBZIeQPn82buywhH-GldDoFqNFm3WPuQJwlHmJysIl9i8q5RlDuHuQsPBLgH3CB5Qul-mMvelMqFzvADzPFr-s2fBP9xBp8F4w";

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

        headers = new System.Net.WebHeaderCollection();

        url = "https://biampdev.api.crm.dynamics.com/api/data/v9.1/quotes?$filter=quotenumber eq 'QUO-04041-N6Y0'";

        clrObj = System.Net.WebRequest::Create(url);


        request = clrObj;
        request.set_Method("GET");
        request.set_KeepAlive(true);

        request.set_ContentType("application/json");
        utf8    = System.Text.Encoding::get_UTF8();

        byteArrayToken = utf8.GetBytes(token);
        byteTokenStr = System.Convert::ToBase64String(byteArrayToken);

        headers.Add("Authorization", strfmt("bearer %1", byteTokenStr));


        request.set_Headers(headers);

        servicePoint = request.get_ServicePoint();

        System.Net.ServicePointManager::set_Expect100Continue(false);

        System.Net.ServicePointManager::set_SecurityProtocol(System.Net.SecurityProtocolType::Tls12);

        response = request.GetResponse();

        info(any2str(response));

        dataStream = response.GetResponseStream();


        streamRead = new System.IO.StreamReader(dataStream);

        jsonString = streamRead.ReadToEnd();

        info(strFmt("%1",jsonString));

        dataStream.Close();

        response.Close();
    }

I try to Debug the code , But in Line 62 its automatic Exit from The code .

Kindly Help me, where this code is wrong ? If You Guys have any other code for this requirement  ,Then also give me other code.

Thanks 

  • Verified answer
    Martin Dráb Profile Picture
    231,923 Most Valuable Professional on at
    RE: How to consume CRM API GET Method in X++

    You aren't using the same token as in Postman. You take the took and convert it with Base64, which gives you a different string. What if you actually use the same token (token variable instead of byteArrayToken)?

  • PK mishra Profile Picture
    115 on at
    RE: How to consume CRM API GET Method in X++

    Hi Martin,

    Thanks for reply,

    I put Try & Catch block, Then i got message "The remote server returned an error: (401) Unauthorized."  as shown by below code.

    static void AXCRMGET(Args _args)
    {
            int                                                      find;
            str                                                      url,aosUri,activeDirectoryTenant;
            str                                                      activeDirectoryClientAppId;
            str                                                      activeDirectoryClientAppSecret;
            str                                                      postData,activeDirectoryResource;
            str                                                      aadClientAppSecret,oAuthHeader;
            str                                                      returnValue,jsonString,jsondszstr, byteTokenStr;
            System.Net.HttpWebRequest                                request;
            System.Net.HttpWebResponse                               response;
            System.IO.Stream                                         dataStream;
            System.IO.StreamReader                                   streamRead;
            System.IO.StreamWriter                                   streamWrite;
            System.Net.ServicePoint                                  servicePoint;
            System.Net.ServicePointManager                           servicePointmgr;
            System.Net.HttpVersion                                   version;
            CLRObject                                                clrObj;
            Newtonsoft.Json.JsonReader                               reader;
            System.Text.Encoding                                     utf8;
            Counter                                                  countCounter;
            Object                                                   obj;
            Map                                                      data;
            System.Byte[]                                            byteArraynew;
            System.Byte[]                                            byteArray, byteArrayToken;
        
        
            System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();    
            
    
            str  token  = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImpTMVhvMU9XRGpfNTJ2YndHTmd2UU8yVnpNYyIsImtpZCI6ImpTMVhvMU9XRGpfNTJ2YndHTmd2UU8yVnpNYyJ9.eyJhdWQiOiJodHRwczovL2JpYW1wZGV2LmNybS5keW5hbWljcy5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvMzQxYWM1NzItMDY2Yy00NmY2LWJmMDYtYjJkMGM3ZGRmMWJlLyIsImlhdCI6MTY0NzUxMDUzNSwibmJmIjoxNjQ3NTEwNTM1LCJleHAiOjE2NDc1MTQ4NjEsImFjciI6IjEiLCJhaW8iOiJFMlpnWU5oOFY5WHBqbkNxeVBkUFNmcU0yaVluVEI5ZThaZGNMTEg1bitXcUM5MTZWaG9BIiwiYW1y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Uq0dNLWzHA9vjYJP8Uj1KIJi1QmNhWoJ91m-Hg6YtmjPlTKPeAjz7KK_fFrkjpWm-L4SEQjegqc17L5Hgea8ggQUfksXHC1SYxvYnGAPVyl5pFI2FZvDhrOvdT23LJitLv-bLWJeQZjGNQsvIUfvhFxPSG5hXAOg-_b4h8CRyyUPSgcYyidPXMXj38axw";
    
            new InteropPermission(InteropKind::ClrInterop).assert();
    
            headers = new System.Net.WebHeaderCollection();
    
            url = "https://biampdev.api.crm.dynamics.com/api/data/v9.1/quotes?$filter=quotenumber eq 'QUO-04041-N6Y0'";
    
        try{    
            
            clrObj = System.Net.WebRequest::Create(url);
    
    
            request = clrObj;
            request.set_Method("GET");
            request.set_KeepAlive(true);
    
            request.set_ContentType("application/json");
            utf8    = System.Text.Encoding::get_UTF8();
    
            byteArrayToken = utf8.GetBytes(token);
            byteTokenStr = System.Convert::ToBase64String(byteArrayToken);
    
            headers.Add("Authorization", strfmt("bearer %1", byteTokenStr));
    
    
            request.set_Headers(headers);
    
            servicePoint = request.get_ServicePoint();
    
            System.Net.ServicePointManager::set_Expect100Continue(false);
    
            System.Net.ServicePointManager::set_SecurityProtocol(System.Net.SecurityProtocolType::Tls12);
    
            response = request.GetResponse();
    
            info(any2str(response));
    
            dataStream = response.GetResponseStream();
    
    
            streamRead = new System.IO.StreamReader(dataStream);
    
            jsonString = streamRead.ReadToEnd();
    
            info(strFmt("%1",jsonString));
    
            dataStream.Close();
    
            response.Close();
        }
        catch (Exception::CLRError)
        {
        throw error(AifUtil::getClrErrorMessage());
        }
     }
    

    I putted same token in postman, Please see my code & Postman Authorization & Param settings. Where I making mistake.

    Thanks

  • Martin Dráb Profile Picture
    231,923 Most Valuable Professional on at
    RE: How to consume CRM API GET Method in X++

    All right, so you're getting an unhandled exception at line 62, but you have no information about the exception because you forgot to catch it. Do something like this:

    try
    {
        ...
    }
    catch (Exception::CLRError)
    {
        throw error(AifUtil::getClrErrorMessage());
    }

    We can get more details from the exception if needed, but this is a good start.

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

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 293,207 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,923 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156 Moderator

Leaderboard

Product updates

Dynamics 365 release plans