Query Data in Dynamics 365 using Web API

by Sarah McCarthy for Blog
Query Data in Dynamics 365 using Web API

We were recently tasked to write a Web API for one of our clients to retrieve data from their Dynamics 365 (formerly Dynamics CRM) system using the Dynamics Web API.  Our client has a variety of bespoke software solutions they use internally, all of which could in the future need to ask Dynamics 365 some questions.  Therefore, we decided to implement a Web API that could be called from any of the bespoke software solutions, thus providing one portal to Dynamics 365.

 

Getting Started

To get started and query data in Dynamics 365 using Web API, we must first collect a few bits of useful information from the Cloud Dynamics 365 instance.  These can be found in the Developer Resources, namely the Organisation ID.

Written in C#, the minimum requirements to connect to Dynamics 365 using their Web API are:

  • Add the Nuget package Microsoft.IdentityModel.Clients.ActiveDirectory.  (This guide uses version 2.24).
  • Add a reference to System.Web and System.Net.Http.
  • Each query to dynamics will require an HttpClient object.  It is useful to create a generator method to do this, but location of the generator method will depend on your project’s architecture.

We opted to use OAuth to make the intial connection to the Dynamics 365 web services.  Our example:

</pre>
using System;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Web.Configuration;

using Microsoft.IdentityModel.Clients.ActiveDirectory;

 

namespace MinimumCRMWebConnect

{

class Helper

{

public static HttpClient GenerateHttpClientForCRM()

{

HttpClient httpClient = new HttpClient();

AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/4ccb8bab-50fe-476f-9958-ada3065cdff4/oauth2/authorize", false);

UserCredential credentials = new UserCredential("username@domain.com", "SecurePassword"); ////YOUR USERNAME & PASSWORD HERE

AuthenticationResult _authResult = authContext.AcquireToken("https://your-crm-instance.crm#.dynamics.com","crm-instance-id-here-0000",credentials); //YOUR CRM INSTANCE URL & ID HERE

httpClient.BaseAddress = new Uri("https://your-crm-instance.crm#.dynamics.com",    //YOUR CRM INSTANCE URL HERE

httpClient.Timeout = new TimeSpan(0, 2, 0);

httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");

httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");

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

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authResult.AccessToken);

return httpClient;

}

}

}
<pre>

 

This gets us connected to the instance of Dynamics 365 we wish to connect to.

 

Simple Query – Return a Single Account

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Text;

using System.Threading.Tasks;

 

namespace MinimumCRMWebConnect

{

class Program

{

static void Main(string[] args)

{

Guid accountID = new Guid("abb1b0db-22d8-e611-812b-3863bb35cf68");

Console.WriteLine(GetAccountName(accountID));

Console.ReadLine();

}

 

private static string GetAccountName(Guid accountID)

{

using (HttpClient httpClient = Helper.GenerateHttpClientForCRM()) //Using block to ensure the HttpClient is correctly

//disposed of when don

{

HttpResponseMessage response = httpClient.GetAsync("api/data/v8.0/accounts?$select=name&$filter=accountid eq " + accountID).Result;

//Note: this may cause deadlock on a project using a UI thread (such as WinForms or WPF).

//If this code will run from a UI project, use an async method and await, like so:

//HttpResponseMessage response = await httpClient.GetAsync("api/data/v8.0/accounts?$select=name&$filter=accountid eq " + accountID);

 

return response.Content.ReadAsStringAsync().Result; //This gets you the JSON string

}

}

}

}

 

Want to know more?

If you want to read more on this topic take a look at these topics on MSDN:

 

Have a requirement for this project?

If you have a requirement for such a project, then why not get in touch.  Call us on 0333 006 9201, or email projects@quaytechsystems.co.uk.

WPF User Controls in WinForms App
Prev post Private Cloud Hosting - First Customer System Live !

WOW! What a week it has been ... Private Cloud Hosting We recently mentioned on a…

WPF User Controls in WinForms App
Next post WPF User Controls in WinForms App

Yes, we really did this! If you have to maintain a legacy WinForms app, but want…