Sunday, 27 September 2020

Get Api Version in JavaScript for WebApi Requests - Dynamics 365 CE

Hi Everyone,

Today I was reviewing the code that was written an year ago and in most of the places I have seen the code like below.

req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts(3851da21-5ae9-ea11-a817-000d3a5308e0)?$select=accountid,accountnumber,name", true);

If you observe that Version has been hard corded in the request, even though it works perfectly I would say, we can do the same in much more better way by taking  it dynamically.

Here is the way for the same.

    var apiVersion = Xrm.Utility.getGlobalContext().getVersion();
    console.log("API Version :  " + apiVersion);
    var version = apiVersion.substring(3, apiVersion.indexOf(".") - 1);
    console.log("Version : " + version);
 
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v" + version + "/accounts(3851da21-5ae9-ea11-a817-000d3a5308e0)?$select=accountid,accountnumber,name", true);

Hope this helps.
--
Happy 365'ing
Gopinath. 

No comments:

Post a Comment