Programming using WebAPI through C# in Dynamics CRM 2016 (2023)


Stepping towards the enhancement, Dynamics CRM 2016 introduced ‘Web API’ as the new concept which delivers a unique development experience across a wide variety of programming languages, devices, and platforms.

We have earlier explored using WEB API through scripting from within Dynamics CRM environment in this blog.

We noticed quite a few queries coming up in forums about using WEB API through C# in code executed outside of CRM like a portal or other integration apps.

What is the difference?

The key difference lies in authentication. When we use scripts and execute from within Dynamics CRM using web resources, the authentication is automatically passed and we do not have to supply the authentication token header there.

But when we are connecting from outside of CRM context, it is important to authenticate the access credentials before they can connect and perform actions in Dynamics CRM.

Note: Some part of the code provided below has been taken from the Authentication library supplied in the SDK and that was the starting point for us to understand and get this working. We were however not able to get the code to execute as is and we try to explain the issues and resolutions to those through this blog.

Connecting using C# from a windows forms application

Here again, the method to pass authentication token varies depending on whether it is CRM On-Premises or CRM Online or IFD enabled deployment of Microsoft Dynamics CRM 2016.

When using windows forms, we realized that it was important to initiate the code as an async task to establish connection. If you do not initiate an async task, the code block to authenticate fails since that action is async.

So first in the form load, we initiate the Start() asynchronously.

(Video) Dynamics 365 Web API Authentication C# | Dynamics 365 Web API Create Record c#

private void CRUD_Load(object sender, EventArgs e){ Task.WaitAll(Task.Run(async () => await Start()));}

On-Premises Deployment

The following details are set in the config file for On-Premises connection

 <appSettings> <!-- FOR CRM OnPremise--> <add key="EndPointType" value="OnPremise"/> <add key="Username" value="username"/> <add key="Password" value="password"/> <add key="Domain" value="domainname"/> <add key="ServerAddress" value="http://ad10:5555/Testing2016/"/> <!--CRM ONPremise End--> </appSettings>

You need to execute your WEB API requests through the HttpClient object. When creating the object of HttpClient, pass the credentials along as shown in the code block below;

HttpClient httpClient = (new HttpClientHandler() { Credentials = new NetworkCredential(_userName, _passWord, _domain) });//Base url of the CRM For e.g. http://servername:port/orgnamehttpClient.BaseAddress = new Uri(_serviceUri);

Suppose you want to create a record in CRM then we need to create an HttpRequestMessage which needs to be sent.

//Http Request needed to be sent by the HttpClient
HttpRequestMessage request = null;
request = new HttpRequestMessage(HttpMethod.Post, “api/data/v8.0/accounts”); //uri to accounts
request.Content = new StringContent(content.ToString()); //JObject of the data to be posted.
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(“application/json”);

//Send the HttpRequest

Task<HttpResponseMessage> response = httpClient.SendAsync(requestMessage);

//Wait till the Response Execution is complete

//If the response is Successfully executed then it will return the value true
if (response.Result.IsSuccessStatusCode)
catch (Exception err)
throw new Exception(err.Message);

CRM Online

The key to establishing connection in CRM Online, is getting the authentication context and acquiring the token

(Video) Intro to Dynamics CRM - 28 - Web API

 AuthenticationResult result = null; AuthenticationContext authContext;

In CRM Online, the OAuth authentication is performed through the Azure Active Directory. With OAuth the user is presented with the login page to type in the credentials manually, once the user is successfully authenticated, the control is redirected to the application that had invoked the authentication.

The following details are set in the config file for CRM Online connection

 <!-- FOR CRM Online--> <add key="EndPointType" value="OnlineFederation"/> <add key="Username" value=""/> <add key="Password" value="password"/> <add key="ServerAddress" value=""/> <add key="RedirectUrl" value="http://localhost/CrmWebApi"/> <add key="ClientId" value="3b12fde5-d0c1-4bed-b1c2-73b0f336d777"/> <!--CRM Online End-->

You need to pass the authority to the AuthContext

private void DiscoverAuthority(String serviceUri) { try { //Authentication parameters received from Resource Server AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(serviceUri + "/api/data/")).Result; if (!String.IsNullOrEmpty(ap.Resource)) { _serviceUri = ap.Resource; } _authority = ap.Authority; } catch (HttpRequestException e) { throw new Exception("An HTTP request exception occurred during authority discovery.", e); } }

#region If you want to get the Authenticationresult at runtime by manually entering the username & password

// Authenticate the registered application with Azure Active Directory.authContext = new AuthenticationContext(Authority, false);//Result to get the AccessTokenresult = authContext.AcquireToken(_serviceUri, _clientId, new Uri(_redirectUrl)); #endregion

If you see in the above code, we pass the

_serviceUri – CRM Online URL,

_clientId – the client id that is generated for your app when you register it in Azure.

_redirectUrl – The URL that the control should be redirected to once the user is successfully authenticated

We can also pass the credentials of a valid CRM user if we do not want the login prompt to show up.

(Video) Dynamics WebAPI

#region Code to pass the Username & Password through Appconfig//// Authenticate the registered application with Azure Active Directory.authContext = new AuthenticationContext(Authority, false);//User Credentials from the AppConfigUserCredential cred = new UserCredential(_userName, _passWord);////Result to get the AccessTokenresult = authContext.AcquireToken(_serviceUri, _clientId, cred);#endregion

Once you have the Authentication Result, you can prepare the HttpClient as below:

HttpClient httpClient= null;httpClient = new HttpClient(); //Default Request Headers needed to be added in the HttpClient ObjecthttpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); //Set the Authorization header with the Access Token received specifying the Credentials httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _result.AccessToken);

Steps for registering the App in Azure to get the ClientID:

For Online CRM deployment models, it seems to be a tricky process as we need to use OAuth to authenticate the user to Azure Active Directory and hence we need to register the App on Azure to get the ClientId & Redirect URL which will be used for Azure authentication.

Steps for registering the App in Azure:

If you have a trial online CRM then you also need to have an Azure subscription. You may get the trial account for Azure using the credentials for Office 365 by signing up from this link. Make sure to sign up in the same tenant.

After you have signed up for Azure go to the Azure portal i.e. and navigate to ‘Browse’ and click ‘Active Directory’. You are then directed to the page as shown in the screenshot below.

From the left-hand side after selecting ‘ACTIVE DIRECTORY’, you are able to find the Active Directory which is created for the Organization. Click and open the active directory.

At the bottom click ‘ADD’ to add the application. A pop up would then get displayed on the screen.

Give a name for the App and select ‘NATIVE CLIENT APPLICATION’ and proceed to the next step.

You then need to specify the Redirect Url which can be used in the Code later as above.

Your App as seen in the screenshot below is now ready.

(Video) Session 5: How to Start working with Custom WebAPI in Dynamics 365

Next, click ‘CONFIGURE ACCESS TO WEB APIS IN OTHER APPLICATIONS’ followed by ‘Configure it Now

You will then get directed to the screen as shown below:

Here you can see the Client ID and Redirect URL which needs to be used in the code further.

As you scroll down, you can view the web page as shown below.

After clicking ‘Add application’ you would be directed to a screen which displays the list of Microsoft Apps.

Select the Dynamics CRM Online option and add it. Next, the screenshot as below lets you provide the access to the user you wish.


Hope the above code snippets along with the logic helps you to perform various operations through the Web API using C#. We have referred to the blog posted under Microsoft’s Developer Network for creating our WebApiHandler class.

[su_heading size=”15″ margin=”5″]Cut short 90% of your manual work and repetitive data entry![/su_heading]

Get 1 Click apps and say goodbye to all repetitive data entry in CRM –
Click2Clone – Clone/Copy Dynamics 365 CRM records in 1 Click
Click2Export – Export Dynamics 365 CRM Report/CRM Views/Word/Excel template in 1 Click
Click2Undo – Undo & Restore Dynamics 365 CRM data in 1 Click


How do I create a Web API in Dynamics 365? ›

There are different HTTP request methods for CRUD operations: Create: POST. Retrieve: GET.
Delete: DELETE.
  1. Create Request Using Web API : Create a custom entity “new_testentity” using the Web API and the XMLHttpRequest object. ...
  2. Retrieve Request Using Web API: ...
  3. Update Request Using Web API: ...
  4. Delete Request Using Web API:

Which programming language is used in Microsoft Dynamics CRM? ›

As we mentioned, X++ is the main programming language of Dynamics AX, now rebranded as Dynamics 365 for Finance and Operations. This programming language powers all the items and elements that you can find within this Microsoft environment. Such as classes, forms, queries, data types, etc.

What is Web API in MS CRM? ›

The Customer Engagement Web API provides a development experience that can be used across a wide variety of programming languages, platforms, and devices. The Web API implements the OData (Open Data Protocol), version 4.0, an OASIS standard for building and consuming RESTful APIs over rich data sources.

How do I connect to Dynamics API? ›

Configure and Connect the Microsoft Dynamics API
  1. Prerequisites.
  2. Step 1: Create Custom OAuth Application in Microsoft Azure.
  3. Step 2: Configure Global Audit Settings. ...
  4. Step 3: Create an Application User under Power Platform Admin Center.
  5. Step 4: Create Security Role for the Application User.
31 May 2022

How do I create my own Web API? ›

How to Create an API
  1. Determine Your Requirements. First, you'll need to determine your API requirements. ...
  2. Design Your API. Next, you'll need to consider API design. ...
  3. Develop Your API. Now, it's time to start developing your API. ...
  4. Test Your API. ...
  5. Publish/Deploy Your API. ...
  6. Monitor Your API.
25 Feb 2021

Does Microsoft Dynamics CRM have an API? ›

Dynamics 365 REST APIs

Dynamics 365 unifies the capabilities of CRM business software and ERP systems by providing intelligent applications that seamlessly work together in the cloud.

What is the best programming language for CRM? ›

CRM developers work with databases, programming languages such as Java or JavaScript, scripting languages such as Perl or PHP, relational databases and data modeling tools like Oracle SQL Developer.

What are the 4 dynamic programming languages? ›

Popular dynamic programming languages include JavaScript, Python, Ruby, PHP, Lua and Perl.

What are the 3 main areas in Dynamics CRM? ›

Microsoft Dynamics CRM has three comprehensive functional modules: Sales, Marketing, and Service (or Customer Care).

What are the 4 main types of Web APIs? ›

Four types of web APIs

APIs are broadly accepted and used in web applications. There are four principal types of API commonly used in web-based applications: public, partner, private and composite.

What is the difference between API and Webapi? ›

Web service is used for REST, SOAP, and XML-RPC for communication, while API is used for any style of communication. Web service supports only HTTP protocol, whereas API supports HTTP/HTTPS protocol. Web service supports XML, while API supports XML and JSON. All Web services are APIs, but all APIs are not web services.

Is Dynamics CRM hard to learn? ›

Learning Dynamics 365 is hard, you are challenged to come up with solutions to deliver customer requirements. You are pushed out of your comfort zone into the uncomfortable place called the Project delivery zone. Suck it up, breath it in and use it to get better quicker.

How do I find my Dynamics 365 Web API URL? ›

In this quick post, we will see how to get the Web API URL for the Dynamics 365 organization.
  1. Go to Settings > Customizations > Developer Resources.
  2. In the Service Root URL, you will find the API URL.
  3. You can copy this URL and paste it into a browser to get its result.
30 May 2022

Which web API is best? ›

Most Popular API Integrations
  • Skyscanner Flight Search – Learn More.
  • Open Weather Map – Learn More.
  • API-FOOTBALL – Learn More.
  • The Cocktail DB – Learn More.
  • REST Countries v1 – Learn More.
  • Yahoo Finance – Learn More.
  • Love Calculator – Learn More.
  • URL Shortener Service – Learn More.
20 Aug 2022

Is there coding in Microsoft Dynamics? ›

You can learn Dynamics 365 without having any coding knowledge and work as Functional Consultants or end-users. However, if you want to be a Technical Consultant, you must understand the fundamentals of C# . NET, HTML, and JavaScript.

What is Dynamics CRM called now? ›

Microsoft Dynamics 365 was officially released on November 1,2016 as the successor to Dynamics CRM. The product combines Microsoft business products (CRM & ERP Dynamics AX).

Is dynamics better than Salesforce? ›

Salesforce is generally more user-friendly in the UI department, and more customizable, but Microsoft Dynamics 365 is probably a bit easier to use for reporting. Then again, if you really want or need an on-premise deployment, a Microsoft Dynamics 365 plan is the only way to go—Salesforce is cloud-based, full-stop.

Which is the No 1 programming language? ›

JavaScript is the most common coding language in use today around the world. This is for a good reason: most web browsers utilize it and it's one of the easiest languages to learn. JavaScript requires almost no prior coding knowledge — once you start learning, you can practice and play with it immediately.

What are the 5 main coding languages? ›

To help you out, here are the top 5 programming languages for developers to get a grip on in 2022.
  • 1 Python. Python is the simplest language that can be learned by beginners. ...
  • 2 C/C++ C/C++ is used by people who continue to work on Microsoft and Windows. ...
  • 3 Java. ...
  • SQL. ...
  • Javascript.
2 Jul 2022

What are the 3 key types of CRM systems? ›

The three types of CRM systems are operational, analytical and collaborative.

Is C# a dynamic programming language? ›

C#, prior to 4.0, is a statically bound language and hence is not a dynamic language.

Is C# a dynamic language? ›

Programming languages are sometimes divided into statically typed and dynamically typed languages. C# and Java are often considered examples of statically typed languages, while Python, Ruby and JavaScript are examples of dynamically typed languages.

What are the 4 pillars of CRM? ›

A successful implementation of CRM is majorly built on four pillars such as workforce, strategy, processes and technology. To design any CRM process we need to consider each of these elements which if ignored, may result in failure of CRM implementation.

What are the five components of CRM? ›

5 Main CRM System Components
  • Database. A database is the most important component of the CRM system, that stores client information and other data required by organizations to carry out their business activities. ...
  • 2 Data Warehousing. ...
  • 3 Data Mining Tools. ...
  • 4 Business Intelligence Tools. ...
  • Social Media Network.
25 Feb 2022

How many data types are there in CRM? ›

Currently, Microsoft supports 14 data types in field are as follows. lets have a brief look on each that is available. 1. Single Line of Text: This field can contain up to 4,000 text characters and can set the maximum length to be less than this limit.

Are all APIs JSON? ›

The vast majority of APIs today are using the JavaScript Object Notation (JSON) to represent the structured data that they are exchanging.

What are the 3 types of APIs and give examples for each? ›

There are also three common types of API architectures: REST, a collection of guidelines for lightweight, scalable web APIs. SOAP, a stricter protocol for more secure APIs. RPC, a protocol for invoking processes that can be written with XML (XML-RPC) or JSON (JSON-RPC).

Which API is most used? ›

Social media APIs are among the most commonly used web APIs. They allow developers to access data from social media platforms like Facebook and Twitter. Each social media platform has its own API that developers can use to interact with the platform's data.

Is JSON an API? ›

JSON (JavaScript Object Notation) API is an application programming interface designed for lightweight data interchange (text-based data exchange format) between two computer applications operating on the same hardware device or between different computers in different geographical areas.

What is another name of API? ›

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other.

How does a Web API work? ›

Most web APIs sit between the application and the web server. The user initiates an API call that tells the application to do something, then the application will use an API to ask the web server to do something. The API is the middleman between the application and the web server, and the API call is the request.

What is web API and why we use it in C#? ›

It is considered a very important tool for developers to build dynamic web pages using languages like C# and Visual Basic. ASP.NET Web API is a framework that helps you to build services by making it easy to reach a wide range of clients including browsers, mobiles, tablets, etc.

What is REST API C#? ›

In simple terms a REST API allows applications to interact with each other and exchange data. For example, let's say you are building a mobile application or a web application. In that application you want to display weather data like temperature, humidity, wind speed etc.

What are the advantages using web API? ›

WEB API is a better choice for simpler, light weight services. WEB API can use any text format including XML and is faster than WCF. WEB API can be used to create full-blown REST Services. WEB API doesn't require any data contracts and doesn't require configurations to the level of WCF.

Is there any coding in CRM? ›

Just like any other area of software development, CRM development requires coding.

How does API connect to server? ›

Here's how an API works:
  1. A client application initiates an API call to retrieve information—also known as a request. ...
  2. After receiving a valid request, the API makes a call to the external program or web server.
  3. The server sends a response to the API with the requested information.
19 Aug 2020

How do I integrate CRM into my website? ›

Plug your CRM directly into your website

By installing connectors between your website and your CRM and building simple to use visitor tools, you can invite your visitors to submit lead enquiries, update their profile information, book a time-tabled session or a carry out a hundred other activities.

Does CRM pay well? ›

Salary Ranges for Crm Managers

The salaries of Crm Managers in the US range from $23,837 to $640,331 , with a median salary of $114,981 . The middle 57% of Crm Managers makes between $114,981 and $289,927, with the top 86% making $640,331.

Is SAP better than dynamics? ›

The main difference between the two is that dynamics are ideal for retail users and SAP is ideal for large enterprises. Microsoft Dynamics has reliable quality control, proper product development functions, and order processing while SAP is more flexible to use due to its intuitive user interface.

Is CRM a good career? ›

According to it Consulting, CRM systems are expected to be the most profitable corporate software segment by 2023; big enterprises and small companies are making significant investments in such systems. They will require people capable of making those systems function correctly.

What is your API URL? ›

An API URL Path is an address that allows you to access an API and its various features. If you've ever used a computer in your life (which I'm sure you have, since you're reading this), you should have at least some idea of what a URL is — even outside the context of APIs.

Where is my API Endpoint URL? ›

Through the dataset URL: You can get the API endpoint by simply taking the dataset's UID and replacing it in this string: https://domain/resource/UID.extension *where the extension is the data format you's like to pull the data as. For a full list of extension formats please go here.

How do I create a Webhook in Dynamics 365? ›

Register Webhook in Dynamics 365 CRM
  1. In the menu, select Register a Webhook option.
  2. Now, you can go ahead and add a Step just like you would do in a Plugin assembly. ...
  3. And, when you Associate a record, example – Assigning a security role to a User –
  4. The Webhook will call the HTTP Request Flow.
23 Nov 2021

How do I use Web resources in Dynamics 365? ›

Create and edit web resources
  1. Open solution explorer, and then select Web Resources.
  2. Under Components, choose Web Resources.
  3. To create a web resource select New. ...
  4. The web resource form has the following fields and capabilities: ...
  5. After you have added your changes, choose Save and then Publish.
15 Feb 2022

How do I find my Dynamics 365 API URL? ›

In this quick post, we will see how to get the Web API URL for the Dynamics 365 organization.
  1. Go to Settings > Customizations > Developer Resources.
  2. In the Service Root URL, you will find the API URL.
  3. You can copy this URL and paste it into a browser to get its result.
30 May 2022

How does Dynamics CRM integrate with website? ›

  1. Step 1 – Create Your Form Fields in Dynamics CRM/ClickDimensions. ...
  2. Step 2 – Design Your Web Form in Dynamics CRM/ClickDimensions. ...
  3. Step 3 – Setting up Form Confirmation Text and Actions. ...
  4. Step 4 – Embedding the Form on Your Website. ...
  5. Step 5 – Test Your Form.
8 Jan 2016

Can we use HTML for dynamic website? ›

Dynamic HTML can work with HTML, JavaScript, XML, and CSS to create dynamic and interactive web pages. Dynamic HTML allows developers to generate effects on a page that would otherwise be impossible. In addition, it allows programmers to use a combination of website creation and animation technologies.

What is an iFrame in Dynamics CRM? ›

In Microsoft CRM Dynamics 365 the iFrame & web resource configuration controls embed the content from another external location in pages with help of html iFrame element. In simple words you can use an iFrame to display the content from another external website in your CRM form.

How do I create a webhook in C#? ›

Using webhooks via your local machine
  1. Setup an MVC Web Application. To get started, we're going to setup a simple webhooks MVC demo app in Visual Studio using C#. ...
  2. Add NuGet Packages. ...
  3. Create a new Controller. ...
  4. Run the Application. ...
  5. Use Conveyor. ...
  6. Conclusion.

How do you write a webhook in C #? ›

How to make a "webhook"?
  1. created the project "ASP.NET Web Application (. NET Framework)";
  2. chose a template - "Empty" + "MVC" + "API";
  3. added controller "Controller MVC 5 - empty". Controller name "HookController";
  4. I run the application "Postman";
  5. "Postman". ...
  6. "Postman". ...
  7. The result, see the picture "- = RESULT = -";
2 Jul 2019

Is webhook same as API? ›

Here's a quick explanation of how webhook compare to API: An application programming interface (API) is a software interface that serves as a bridge between computers and applications. A webhook is a way for one application to deliver data to another app in real-time.

How many types of Web Resources are there? ›

5-7 Types of web resources | Learning Information Veracity @ RIT | RIT.

How do you consume the external Web API or web service from Dynamics 365? ›

In this article
  1. Create a new Class Library project in Visual Studio, and name it ExternalServiceLibrary. csproj.
  2. Build the project. ...
  3. Create a new Dynamics project in Visual Studio.
  4. Add ExternalServiceLibrary. ...
  5. In the X++ class, you can use the external web services that were referenced in ExternalServiceLibrary.
1 Jul 2022

What are the different web resource supported by CRM? ›

The types of Web Resources in Microsoft Dynamics CRM are WebPage (HTML), Script (JScript), Style Sheet (CSS), Data (XML), Image (PNG,JPG,GIF, ICO), Silverlight (XAP), StyleSheet (XSL).

What is API URL example? ›

API Server and Base URL. All API endpoints are relative to the base URL. For example, assuming the base URL of , the /users endpoint refers to . In OpenAPI 3.0, you use the servers array to specify one or more base URLs for your API.


1. Dynamics 365 WEB API CRUD
2. CRMOnce: How to Consume the External Web API or Webservices from Dynamics 365(CRM)Plugin
(CRMONCE - Power Platform Solutions)
3. Intro to Dynamics CRM - 25 - Querying CRM Using C#
4. Getting Started with Web API in Dynamics 365 CE /CRM | Magnifez Academy
(Magnifez Academy)
5. Console Application CRUD Operation in C# in Dynamics 365
(Softchief Learn)
6. Connect Dynamics 365 using Postman using WEBAPI
(Softchief Learn)
Top Articles
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated: 01/02/2023

Views: 6037

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.