Let’s Play with WEB API – Part -1 : Retrieve Multiple Records

Retrieve Multiple  Records using Web API

The Web API is a newly introduced open standard endpoint currently available in CRM 2016  at [organization uri]/api/data/v8.0/ which implements ODATA v4 and allows you the full blown functionality that you would typically experience when interacting through the CRM Organisation Service.

The Web API service is said to eventually replace the existing Organisation and Organisation Data service and MS recommend that if you writing new code that you begin using the Web API endpoint as the existing ODATA REST endpoint is officially deprecated but still available for backward compatibility.

The new API has introduced some impressive functionality that was not available to us previously with the existing ODATA service. Some of that functionality includes:

  • Ability to execute saved queries
  • Ability to execute FetchXML
  • Use Queries Up to Second Level

Following code shows how to retrieve records using web API, I have tested to retrieve 2000+ records and it is working fine.

This code alerts the number of contacts under an Account entity.

function AccountOnLoad()

{

    var Id = Xrm.Page.data.entity.getId().substring(1, 37);

    var entity = "contacts";

 var columnSet = "?$select=firstname&$filter=_accountid_value eq " + Id + "&$count=true";

    var options = columnSet;

  

    var serverURL = Xrm.Page.context.getClientUrl();

    var Query = entity + options;

    var req = new XMLHttpRequest();

    req.open("GET", serverURL + "/api/data/v8.0/" + Query, true);

    req.setRequestHeader("Accept", "application/json");

    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

    req.setRequestHeader("OData-MaxVersion", "4.0");

    req.setRequestHeader("OData-Version", "4.0");

    req.onreadystatechange = function () {

        if (this.readyState == 4 /* complete */) {

            req.onreadystatechange = null;

            if (this.status == 200) {

                var data = JSON.parse(this.response);

                if (data['@odata.count'] != null)

                    alert("This Account Has" + data['@odata.count'] + "Contacts");

            } else {

                var error = JSON.parse(this.response).error;

                alert(error.message);

            }

        }

    };

    req.send();

}

 

There are many other features too which I will be demonstrating in the upcoming posts.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s