Retrieve record using Web API – CRM 2016

Hi,

We all know with CRM 2016 we should use Web API instead of oData in JavaScript. Here is the sample code for creating a record using Web API.

function getPrimaryContact() {

    var clientUrl = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest();
    req.open(“GET”, encodeURI(clientUrl + “/api/data/v8.0/contacts?$select=fullname,emailaddress1&$filter=fullname eq ‘I am the Primary Contact'”), 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);
                var dat = data.value;
                // Loop through ‘Contact’ result set
                for (var i = 0; i < dat.length; i++) {
                    // Get ‘Contact ID’ from Contact record.
                    var contactId = dat[i].contactid;
                    var emailAddress = dat[i].emailaddress1;
                    if (contactId) {
                        Xrm.Utility.alertDialog(“Email Address : “ + emailAddress);
                        // Xrm.Utility.alertDialog(“Contact ID : ” + contactId);
                    }
                }
            }
            else{
                var error = JSON.parse(this.response).error;
                alert(“Error retrieving contact – “+ error.message);
            }
        }
    };
    req.send();
}

Hope this helps.

Happy CRM’ing

Gopinath

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s