Getting started with CRM 2011 JavaScript REST (OData) Web Service Calls

So I’m not going to present anything revolutionary here, but recently I had to do just this. Back in the CRM 4 world I was performing all my web service calls against the SOAP endpoint of CRM, with the move to 2011 I knew the world of REST had arrived but up until a couple of weeks ago I never really had the need to use it in any anger.

So this post is basically how I brought together various resources on the web to get started with REST calls from JavaScript. In some ways this is a bit of brain dump, but hopefully you might find it useful.

So first off some general background information on REST and CRM, I won’t get into too much detail here the information is already on the web and I’d rather not just reproduce it for the sake of filling space.

Use the REST Endpoint for Web Resources

“REST is an architectural style in which every resource is addressed by using a unique URI. In Microsoft Dynamics CRM, a resource can be an entity collection or a record.”

“Microsoft Dynamics CRM 2011 uses the Windows Communication Foundation (WCF) Data Services framework to provide an Open Data Protocol (OData) endpoint that is a REST-based data service. This endpoint is called the Organization Data Service.”

“The REST endpoint provides an alternative to the WCF SOAP endpoint, but there are currently some limitations.”

In terms of limitations the two (there are more) main parts that jump to mind are:

  1. With REST you can’t do everything SOAP can do. In REST you cannot perform actions that involve; assigning, metadata and execute messages (e.g. CreateRequest). However you can perform all the standard create, retrieve, update and delete (CRUD) calls, and associating and disassociating (AD) records.
  2. CRM’s implementation of OData hasn’t implemented every feature of the OData protocol, the most obvious being ‘count’.

Use Web Service Data in Web Resources (REST and SOAP Endpoint)

All of this information is available from the MSDN so check out the provided links and drill down to the other articles because there really is a wealth of information on there.

For those who have been excited into a state of near ecstasy by all this talk of OData, REST or SOAP you can get more information from places like this OData.org or this How I explained REST to my wife or StackOverflow SOAP v REST.

The gist of all that is, we can use OData from JavaScript to chat to CRM.

I was expecting that I would be forming all the OData calls from scratch and would eventually develop examples I found into a personal library. I started off by digging through various MSDN samples until I came across Sample: Create, Retrieve, Update and Delete Using the REST Endpoint with JavaScript and jQuery.

This was basically everything I wanted, it had examples of performing CRUD web service calls, capturing the results and doing things with them.

Even better it has a library ‘SDK.JQuery.js’ which encapsulated all the web service stuff. I’ve used that library quite a bit now and I’ve found it very reliable and if you want to get something moving quickly I would whole heartedly recommend it. If you are more interested in doing this totally from scratch that script should hopefully work as an excellent base for your work.

Make sure to read ‘JQueryRESTDataOperationsSample.js’ which gives an example of how to perform all the operations using the library and parse the results.

Note: For those jQuery adverse there is also a non-jQuery sample on the MSDN.

So the rest of this post is basically how I took that sample and turned it into something I could use easily in CRM, fortunately this isn’t a lot of work.

  1. Copy the contents of ‘SDK.JQuery.js’ into a JavaScript web resource within CRM. This script contains all the web service call stuff.
  2. ‘SDK.JQuery.js’ has a dependency on JQuery – its uses the Ajax functionality to perform web service calls. Go to JQuery and download JQuery and load that as a web resource in CRM.
  3. ‘SDK.JQuery.js’ will return results as JSON (as opposed to ATOM) so we need to include that as well, go to json2, download and load that into CRM as a web resource.

If you do all that you should end up with something like this:

odata1

So to actually use SDK.JQuery create another JavaScript web resource which will hold your code. I’ve named mine Gap.Test, for now put this code into the web resource.

var Gap = Gap || {};
Gap.Test = {
	GetMrWaffleBite : function() {
		SDK.JQuery.retrieveMultipleRecords( //The function we are calling from the library.
			"Contact", //Entity we are retrieving
			"$select=FullName&$filter=FullName eq 'Waffle Bite'", //The query that will be peformed
			function (results) { //The call back function which will contain the results
				if (results == null || results[0] == null) {
					alert("Mr Waffle Bite was not found.");
				}
				else {
					alert("Found " + results[0].FullName);
				}
			},
			function (error) { alert(error) }, //An error handler
			function () {} //On complete handler
		);
	}
};

This code uses SDK.JQuery to find a contact named Waffle Bite, I’m sure you will agree that this is very useful functionality and also helps to illustrate my point here.

Setup the form scripts like so (I’ve used the fax entity here but you can use anything you want).

odata2

Open the fax entity and you should be presented with a screen as follows. Exciting stuff.

odata3

I really like this approach as the library nicely encapsulates all the web service code, you just have to include a couple of libraries in the form and rest of it is pretty straight forward.

I’m not bothering to explain the actual code here because the MSDN does a good job of it already, I would suggest having a read of the article and looking at the code files – it’s teaching by example.

So before I end I’ll just cover off some pitfalls that I found and how I worked my way through them.

Designing OData queries is tricky.

For my OData queries I used the OData Query Designer from CodePlex, it installs as a solution into CRM and can be used to produce OData queries from a Silverlight interface.

CRM 2011 OData Query Designer.

Bear in mind that when you create a query with this tool it gives you a full URL like so:

https://servername/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId

You will need to remove everything in front of the $ for your query, so you end up with:

SDK.JQuery.retrieveMultipleRecords(“Contact”, “$select=AccountId”, . . .

That OData Query Designer doesn’t work when I execute the query in the designer [Arg_SecurityException].

Yeah I got that as well, I don’t actually know how to fix it either. What you can do is copy the query into the web browser URL bar and it will present the results as an ATOM feed. Hopefully this should be enough to get you going. If your browser presents the information as an RSS feed follow the instructions at the start of this article CRM 2011 OData, JSON and CRM Forms.

Knowing how to parse the result set is tricky.

When I started I found the easiest way to do this was to bring back the result and debug them with IE Debugger (F12). You can then use the console to examine the results, once you have done this a few times it becomes easier to predict the result set.

odata4

It’s complaining my entity/attribute doesn’t exist.

Make sure you have the right casing. OData is case sensitive and you should be using the ‘schema name’ instead of the ‘name’. E.g. FullName instead of fullname.

Additionally when pass your entity to the library functions don’t include ‘set’ even though it is in the designer – the library automatically appends ‘set’.

Right – SDK.JQuery.retrieveMultipleRecords(“Contact”, …

Wrong – SDK.JQuery.retrieveMultipleRecords(“ContactSet

Advertisements

7 thoughts on “Getting started with CRM 2011 JavaScript REST (OData) Web Service Calls

  1. Cannot seem to get this working no error message given. If i add the javascript to a browser console window it returns undefined but doesn’t throw an error.

  2. Pingback: Getting started with CRM JavaScript REST (OData) | transCRMystic

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s