› Dynamics CRM › Microsoft Dynamics CRM 2015 Web API

Microsoft Dynamics CRM 2015 Web API

 Admin   1 Comment

Microsoft has released the Dynamics CRM Web API with the 2015 Spring Update. The purpose of this blog article is to demonstrate the use of the CRM Web API for performing different data operations.

Before we begin using the Web API there are a few pre-requisites.

  1. Azure Subscription
  2. Dynamics CRM 2015 Update 1
  3. Dynamics CRM user with System Administrator role

Next we need to follow the steps given below to start using the Web API:

  1. Enable Web API Preview in CRM.
    1. Web API Preview can be enable in Dynamics CRM 2015 Update 1 from SettingsAdministration > System Settings.
  2. Associate Azure Subscription to your Dynamics CRM Tenant.
    1. You can follow the steps given here to associate your Azure Subscription to your Dynamics CRM tenant.
  3. Register an App on Azure Active Directory.
    1. Log In to Azure and go to Active Directory -> <your directory> ->Applications -> AddAzure App
  1. Click on “Add an application my organization is developing”.
  2. Select “Native Client Application” and enter the name of the application.
  3. Enter the Redirect URI as http://localhost/<yourappname> and then click on Ok.
  4. Once completed you will be redirected to the application page. Click on “Configure Access to Web Apis in other applications” and then click on “Configure it now”.Azure App 1
  5. Click on Add Application and select Dynamics CRM Online and then click on Complete.
  6. Next, Under Delegated Permissions check “Access CRM Online as organization users” and click on Save.
  7. Also copy and save the ClientID and Redirect URI as we will require this is our code.
  1. Create a .Net App to start consuming the Web API
    1. Create a new Console Application project in Visual Studio.
    2. Right Click on the Project and click on Manage NuGet Packages.
    3. Enter “adal” in the search box and then install Active Directory Authentication Library.AppDEmo
    4. This will install the required .dlls to help us authenticate using Azure Active Directory.
    5. Add the below code in the Main() method of your program.
string resource = "https://<yourdomain>.crm.dynamics.com/";
            string clientID = "<your client id>";
            string redirectUrl = "<your redirect uri>";
            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);
 AuthenticationResult result = authContext.AcquireToken(resource, clientID, new Uri(redirectUrl));
  1. Run the code by pressing f5. You will be prompted to enter your user credentials. After entering the credentials the server returns an Authentication Token.AppDemo 1

The AccessToken and the AccessTokenType (“Bearer”) is what we need to include into every Authorization header of http request.

  1. Next into every requests we make to the CRM Web API we need to pass this authentication token. Below is a Sample Code which demonstrates use of CRM Web API for Create, Retrieve, Update and Delete Operations.
using Microsoft.Crm.Sdk.Samples.HelperCode;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WebAPITest.Entities;

namespace WebAPITest
{
    class Program
    {
        static string resource = "https://destroyskynet.crm.dynamics.com/";
        static string clientID = "<your client id>";

        static string redirectUrl = "http://localhost/webapitest";
        static void Main(string[] args)
        {
            
            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);

            Task.WaitAll(Task.Run(async () => await DataOperations(authContext)));
        }

        private static async Task DataOperations(AuthenticationContext auth)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri("https://destroyskynet.crm.dynamics.com");
                httpClient.Timeout = new TimeSpan(0, 2, 0); //2 minutes
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");

                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                Account account = new Account();
                account.name = "Cloudfronts TechnologiesNew";
                account.telephone1 = "555-555";

                string content = String.Empty;
                content = JsonConvert.SerializeObject(account, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore });

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken(resource, clientID, new Uri(redirectUrl)).AccessToken);

                //Create Entity
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "api/data/accounts");
                request.Content = new StringContent(content);
                request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                HttpResponseMessage response =await httpClient.SendAsync(request);
                 if (response.IsSuccessStatusCode)
                        Console.WriteLine("Account '{0}' created.", account.name);
                    else
                        throw new Exception(String.Format("Failed to create account '{0}', reason is '{1}'.",
                                            account.name, response.ReasonPhrase));

                //Retreive Entity
                //The uri of the created entity is received in "OData-EntityId". Use the account URI to update/delete account.
                 string accountUri = response.Headers.GetValues("OData-EntityId").FirstOrDefault();
                 var retrieveResponse = await httpClient.GetAsync(accountUri + "?$select=name,telephone1");
                 Account retreivedAccount=null;
                if(retrieveResponse.IsSuccessStatusCode)
                {
                    //Deserialize response into Account
                    retreivedAccount = JsonConvert.DeserializeObject<Account>(await retrieveResponse.Content.ReadAsStringAsync());
                    Console.WriteLine("Retreived Account Name : {0} Telephone : {1}",retreivedAccount.name,retreivedAccount.telephone1);
                }
                else
                {
                    throw new Exception(String.Format("Failed to retreive account '{0}', reason is '{1}'.",
                                            account.name, response.ReasonPhrase));
                }

                //Update Entity
                JObject accountToUpdate = new JObject();
                accountToUpdate.Add("name", retreivedAccount.name + "Edited");

                string updateContent = String.Empty;
                updateContent = accountToUpdate.ToString();

                HttpRequestMessage updateRequest = new HttpRequestMessage(HttpMethod.Put, accountUri);
                updateRequest.Content = new StringContent(updateContent);
                updateRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                HttpResponseMessage updateResponse = await httpClient.SendAsync(updateRequest);

                if (response.IsSuccessStatusCode)
                    Console.WriteLine("Account '{0}' updated.", accountToUpdate["name"]);
                else
                    throw new Exception(
                            String.Format("Failed to update account '{0}', reason is '{1}'.", accountToUpdate["name"],
                            response.ReasonPhrase));

                //Delete Account
                HttpResponseMessage deleteResponse = await httpClient.DeleteAsync(accountUri);
                if (response.IsSuccessStatusCode)
                    Console.WriteLine("Account deleted.");
                else
                    throw new Exception(
                        String.Format("Failed to delete account"));
            }
        }
    }
}

Microsoft has also provided helper code to authenticate using credentials stored in the .config file. In my next article I will demonstrate how to use this helper code and authenticate users directly using the credentials stored in the .config file.


Liked it? Share it.

One thought on “Microsoft Dynamics CRM 2015 Web API”

  1. Hi,

    My Name is Mohit. Excellent article. Can you provide sample code to invoke “Actions” using WebAPI from JavaScript outside the CRM

Leave a Reply

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

Time limit is exhausted. Please reload the CAPTCHA.