WebAPI in D365 (Using JavaScript) - Part 1

Microsoft Dynamics CRM 2016 introduced the Web API, a new endpoint allowing the creation, deletion, updating and retrieval of CRM data. Web API can be consumable from client side or any 3rd partly Applications like (Function APP, Web APIs, ASP.net).

Use CRM Rest Builder

Available as a managed solution, the CRM Rest Builder provides a straightforward interface for building both 2011 and Web API queries. It’s as simple as selecting the action, format, entity and other details, and then clicking “Create Request.”

CRM Rest Builder: A useful tool for working with CRM 2016’s and D365 Web API

image.png

If webapis use to retrieve multiple records. The value is defaulted to the maximum limit of 5000 records. Can be changed the default retrieve count by maxPageSize parameter. If there are more entities that match the query filter criteria, a @odata.nextLink property will be returned with the results. Use the value of the @odata.nextLink property with a new GET request to return the next page of data.

Web API using Javascript

Code Snippet(Synchronous)

function RetrieveEntityByIdWebApi(RetriveString) {
    var result;
    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Utility.getGlobalContext().getClientUrl()
 + "/api/data/v9.2/" + RetriveString, false); //if Async = false, then operation is Synchronous. Else aynchronous if the flag is true
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                result = JSON.parse(this.response);
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();
    return result;
}

Web API using Xrm.WebApi library(Asynchronous)

Xrm.WebApi.retrieveMultipleRecords("contact", "?$select=firstname&$filter=firstname eq 'Arindam'").then(
    function success(result) {
        for (var i = 0; i < result.entities.length; i++) {
            alert(result.entities[i].firstname);
            // do something
            break;
        }
    },
        function(error) {  
            alert("Error: " + error.message);  
        }  
    );
}

Did you find this article valuable?

Support Arindam Saha by becoming a sponsor. Any amount is appreciated!