Query Dynamics CRM through JavaScript with WebAPI

1 Comment

Following on from Querying Dynamics CRM through JavaScript using the OrganizationService, we will now go through an example using the new Web API.

We will use this URL to get the full web service URL:

var url = Xrm.Page.context.getClientUrl() + "/api/data/v8.1/";

We will use the Id of the record:

var Id = Xrm.Page.data.entity.getId();

Our Web API filter is constructed like below:

https://yourcrm.crm.dynamics.com/api/data/v8.1/leads?$select=lastname

To filter the LeadId our query will be (note no quotes or brackets):

https://yourcrm.crm.dynamics.com/api/data/v8.1/leads?$filter=leadid eq id

Now, we will use XMLHttpRequest to post to the web service and get our response back as JSON. We will confirm we have an http status of 200 (OK).

function QueryCRM() {

var Id = Xrm.Page.data.entity.getId().substring(1, 37);
var url = Xrm.Page.context.getClientUrl() + "/api/data/v8.1/leads(" + Id + ")";

 var req = new XMLHttpRequest();

 req.open("GET", url, false);
 req.setRequestHeader("Accept", "application/json");
 req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 req.send();


 if (req.readyState == 4 /* complete */) {
 //Success 
 if (req.status == 200) {
 alert(req.responseText);
 }
 //Failure
 else {
 alert("Error: " + req.responseText);
 }
 }

}

When we run the page we see:

We can also use JSON.parse to parse the results:

JSON.parse(retrieveReq.responseText).d;

If we want to get the value of a field, we can use:

var res = JSON.parse(req.responseText);
var LastName = res.lastname;
alert (LastName);

If there are errors, debug using:

debugger;

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

One Response to Query Dynamics CRM through JavaScript with WebAPI

Leave a Reply

Your email address will not be published. Required fields are marked *