Dynamics CRM Web API

This page provides a technical overview of the Web API in Dynamics 365 (CRM) and Dynamics CRM 2016.

Features/Functionality

  • For CRM 2016 and beyond, Microsoft recommends the use of the Web API (a RESTful web service) in JavaScript web resources.
    • You interact with the Web API by composing and sending HTTP requests. You need to know how to set the appropriate HTTP headers and handle any errors included in the response.
    • HTTP methods used include GET, POST, PATCH, DELETE and PUT.
    • It uses JSON in the body of the HTTP requests and responses, which makes it very suitable for use with JavaScript.
  • Use the Web API to build a wide variety of client applications (browser, mobile, desktop) and with a variety of different programming languages (JavaScript, C#, Node.js, Python, etc.)
  • Implements OData v4.0, an OASIS standard for building and consuming RESTful APIs over rich data sources.
  • Replaces the need for the current but deprecated "OData Endpoint" (also known as the "2011 endpoint")
  • There are no client dependencies on the Dynamics CRM SDK assemblies
  • Available for CRM Online, on-premises, and Internet-facing deployment (IFD)
  • Perform CRUD (Create, Read, Update/Upsert and Delete) operations

What is a "Web API" (in general)


CRM Programming Model for CRM 2016

New for the Dynamics CRM 2016 programming model is the Web API, which falls under the HTTP Client OAuth connection method.
wiki_crm_programmingmodel_crm2016_sdk.png

Dissecting the acronyms:
  • HTTP: Hypertext Transfer Protocol
  • OAuth: Open Authorization
  • API: Application Programming Interface
  • CSDL: Common Schema Definition Language
  • OData: Open Data Protocol
  • REST: Representational State Transfer
  • JSON: JavaScript Object Notation

Usage Examples/Scenarios

This section contains some common use cases where the CRM Web API is utilized.
  • Create a custom CRM UI using an HTML Web Resource and display it in an IFRAME or dashboard. Use the CRM Web API to save the data entered by the CRM user.
    • A sample data entry web resource is shown below. You can learn about this application on YouTube.
    • Clicking the Save button creates the accounts and contacts in one Web API call using a batch request.
      • wiki_crm_webapi_app_example1.jpg
        Sample HTML Web Resource to utilize CRM's Web API


  • Create a web application and utilize the Web API to perform CRUD operations in CRM Online


Dynamics 365 Instance Web (HTTP REST) API URL

To obtain the HTTP REST API URL for a Dynamics 365 instance, go to Settings >> Customizations >> Developer Resources. The page that appears provides the Service Root URL for the Web API.

Authentication

  • When using the Web API from within the CRM application, no extra authentication is needed.
  • Using CRM Web API outside of the CRM application:

Limitations

  • Limits on number of entities returned
    • Unless you specify a smaller page size, a maximum of 5000 entities will be returned for each request. If there are more entities that match the query filter criteria, a @odata.nextLink property will be returned with the results. Use the value of the @odata.nextLink property with a new GET request to return the next page of data.
  • Microsoft Dynamics CRM Web API Limitations

Dynamics CRM SDK Links for Web API

Below are links to various CRM SDK pages related to the Web API.

Sample Code

Development / Libraries / Testing Tools

There's a growing number of code libraries (mostly JavaScript at this point) that provide wrapper (helper) functions for using the CRM Web API. As with most JavaScript libraries, there's a wide range of coding patterns and styles in the libraries listed below. The recommendation is to choose a library that fits with your existing standards or knowledge, test it in a CRM sandbox environment and consider using it as-is or adapting it to meet your needs.


Use LINQPad with CRM Web API

LINQPad 4 Driver for Dynamics CRM REST/Web API are available on CodePlex

Sample JavaScript Code to Retrieve Account Records

The JavaScript code below uses XMLHttpRequest to retrieve account records where the state = "WA", the customer type is "Customer", the record is active and the modified date is on or before 12/31/2014.
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/accounts?$select=name,_primarycontactid_value,telephone1&$filter=address1_stateorprovince eq 'WA' and  customertypecode eq 3 and  statecode eq 0 and  modifiedon le 2014-12-31T08:00:00.000Z&$orderby=name asc&$count=true", true);
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=\"OData.Community.Display.V1.FormattedValue\"");
req.setRequestHeader("Prefer", "odata.maxpagesize=50");
req.onreadystatechange = function () {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 200) {
            var results = JSON.parse(this.response);
            var recordCount = results["@odata.count"];
            for (var i = 0; i < results.value.length; i++) {
                 var name = results.value[i]["name"];
                 var _primarycontactid_value = results.value[i]["_primarycontactid_value"];
                 var _primarycontactid_value_formatted = results.value[i]["_primarycontactid_value@OData.Community.Display.V1.FormattedValue"];
                 var telephone1 = results.value[i]["telephone1"];
            }
        }
        else {
            alert(this.statusText);
        }
    }
};
req.send();

Reference: Web API OData query syntax

Building and Running the "Basic Operations" C# Example from Microsoft

In August 2016, Microsoft released sample code for using the Dynamics CRM Web API from JavaScript and C# for applications that are external to CRM and require authentication. This section provides details on getting the "Basic Operations" C# sample application up and running with Dynamics CRM Online.

Prerequisites
  • Microsoft Dynamics CRM Online 2016
  • Microsoft Azure subscription
  • Microsoft Visual Studio 2015 or newer
  • Required user accounts
    • Azure: Ability to make changes in Azure Active Directory
    • CRM Online: Office 365 administrator

Steps
  1. Download the Visual Studio solution and extract the zip file to your local machine.
  2. Open the solution (BasicOperations.sln). Then open the NuGet Package Manager and update the Microsoft.CrmSdk.WebApi.Samples.HelperCode package (as of this writing, the latest version is 8.1.0.7, but update to the newest version).
  3. Build the solution but don't run it yet. It's necessary to update the app.config with your CRM Online connection details and an Azure AD application id (client id).
  4. In order for the application to connect to Dynamics CRM Online, it is necessary to create an application record in Azure Active Directory. The sample console application will authenticate with Azure AD and provide a token to CRM; this allows the console application to utilize the CRM Web API.
    1. If your Azure subscription and CRM Online instance are not on the same tenant (e.g., you signed up for a personal Azure account to try this sample), then you must connect Azure AD to Dynamics CRM's tenant
    2. Follow this article to register the BasicOperations sample application with Azure AD: Walkthrough: Register a CRM app with Azure Active Directory
  5. Update the app.config file with your CRM Online connection details. Also, provide the ClientId from the new Azure AD application you created.
    1. Reference: Web API Helper code: Configuration classes
    2. Note: For the connectionString parameter (where you enter your CRM Online URL), be sure to end the URL with a forward slash, otherwise the sample application will throw an error.
  6. Run the application in debug mode and step through the code to gain an understanding of the OAuth-based CRM connection and usage of the CRM Web API.

Other/Misc

  • To obtain the URL for the CRM organization's Web API, go to Settings >> Customizations >> Developer Resources. The Service Root URL is under "Instance Web API".