Retrieve Data Using CRMWebAPI With Webresource In Dynamics CRM

Introduction

In Dynamics 365 CRM, for certain requirements data needs to be retrieved to achieve business functionality with Web API. As an example, selected contact record guid was passed to fetch details of contact.

Step 1

Login to the required environment and select required solution [Contact Customizations Solution in this case] as shown in the below figure.

Retrieve Data Using CRMWebAPI with Webresource in Dynamics CRM

Step 2

After Step 1, select contact web resource in solution and click on Edit as shown in the below figure.

Retrieve Data Using CRMWebAPI with Webresource in Dynamics CRM

Step 3

After Step 2, in JavaScript file(webresource) use the below code to fetch the contact GUID for a selected record

let contactGUID=Xrm.Page.data.entity.getId().replace("{","").replace("}","");

Step 4

After Step 3, prepare URL with the combination of URL of Dynamics CRM environment and frame web API path by passing dynamic contactGUID with the below code

var finalurl = encodeURI(Xrm.Page.context.getClientUrl() + "/api/data/v9.2/contacts("+contactGUID+")");

Step 5

After Step 4, pass this final URL to the request and frame the request by passing all the required headers and if we get response with 200 status code then show the full name of the contact with the below code

var data = null;
var isAsync = false;
var req = null;
if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
req.open("GET", finalurl, isAsync);
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) {
            data = JSON.parse(this.response);
            if (data != null) {
                Xrm.Utility.alertDialog("Full Name:" + data.fullname);
            }
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send();

Step 6

After Step 5, the final code looks like below

ContosoVaccination.Scripts.ContactForm = {
    handleOnLoad: function(executionContext) {
        console.log('on load - contact form');
        getContacts(executionContext);
    },
    __namespace: true
}

function getContacts(executionContext) {
    let formContext = executionContext.getFormContext();
    if (formContext !== null && formContext != 'undefined') {
        let contactGUID = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
        var finalurl = encodeURI(Xrm.Page.context.getClientUrl() + "/api/data/v9.2/contacts(" + contactGUID + ")");
        var data = null;
        var isAsync = false;
        var req = null;
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        req.open("GET", finalurl, isAsync);
        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) {
                    data = JSON.parse(this.response);
                    if (data != null) {
                        Xrm.Utility.alertDialog("Full Name:" + data.fullname);
                    }
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
    }
}

And register this function on load event in contact form and save and publish it.

Step 7

After Step 6, open any contact record and observe full name is shown as a dialog.

Retrieve Data Using CRMWebAPI with Webresource in Dynamics CRM

Note

  1. Make sure to publish all customizations and upload JavaScript (js) file.
  2. Make sure the final URL was well formed otherwise lead to errors.
  3. As my concentration is on explaining way to fetch data with web API I have not explained way to register onload event in contact form.

Conclusion

In this way, one can easily fetch contacts data for a selected contact record using CRM Web API.