Implement Dynamics REST API using Node.js [Tutorial]

Written by Dhemie | Published 2019/10/22
Tech Story Tags: microsoft-dynamics | nodejs | typescript | api | azure | dynamic-rest-api | azure-active-directory | latest-tech-stories

TLDR Microsoft Dynamics 365 is a cloud-based business applications platform that combines components of customer relationship management (CRM) and enterprise resource planning (ERP) with productivity applications and artificial intelligence tools. In this post, I’d show you how to implement the Rest API provided by dynamics. The main challenge comes when trying to procure access credentials for Dynamics CRM’s CRM. This tutorial up to the point of obtaining access credentials would apply to them also. The code sample code consists of two typescript files, the dynamics service, dynamics service and an app.via the TL;DR App

Microsoft Dynamics 365 is a cloud-based business applications platform that combines components of customer relationship management (CRM) and enterprise resource planning (ERP), along with productivity applications and artificial intelligence tools, although currently Dynamics is more popular for its CRM capabilities. 
Sometimes as with many other enterprise grade applications, the need may arise to abstract some activities from the main application itself, for example creating a mobile app to perform operations or have a need to communicate with dynamics outside the dynamics application.
 In this post, I’d show you how to implement the Rest API provided by dynamics, this sounds easy enough, but the main challenge comes when trying to procure access credentials.
This was a very painstaking process, resources that guides you through this sadly are not put together in one place, pieces of information from different sources (videos, articles, official docs) had to be put together as it proved difficult getting a single resource that offered an end to end guide. This post hopefully would save someone a lot of time and hair pulling.

Azure Active Directory

The Azure Active Directory (Azure AD) is Microsoft’s cloud-based identity and access management service, in simple terms, its like a global auth service for most of Microsofts products, customers using Microsoft 365, Office 365, Azure, or Dynamics CRM Online subscribers already have Active Directory setup for them, this tutorial up to the point of obtaining access credentials would apply to them also.
Phase 1 (Setup Dynamics)
The first step is to create a dynamics account if you don’t have access to one already, you can sign up for a free one month trial here, note that you would need an email with a domain you can manage, this is necessary as you’d need to update the domains TXT record to manage the dynamics account with admin privileges.
After creating your dynamics account, on the dashboard click on the menu button at the top right corner, and then click the admin button
You’d be asked to verify your email domain, follow the steps provided and verify your email. 
Phase 2 (Access Credentials)
 As explained earlier, Dynamics CRM’s authentication is managed under the Azure’s Active Directory, so we’d have to access the Azure portal to get the needed AAD credentials.
This doesn’t mean you’d have to create an account on Azure, as explained earlier AAD is a global auth service for Microsoft products and SAAS’s, so you can sign right into the Azure portal here using the same login credentials you use for your dynamics service. 
Step 1 Get Client ID and Secret
On the side menu, click on Azure Active Directory
2. click on App Registrations then New Registration
3. Fill in the required details, select the account access option that applies to your application needs 
4. On the overview page, copy the client id and tenant id also
5. click on manifest, and change the value of “allowPublicClient” from null to true and then save
6. Next, on the menu tab click on API permissions and then add permission, select the dynamics CRM option and then check the user impression option. if you are following this tutorial for other services, you can select your service here
7. On the next page, click on the “Grant admin consent for <your domain>” button
And that’s it for the phase 1, what we have done so far is to
Get credentials for our apiGrant access to dynamics crm from our api
Remember these credentials isn’t just limited to Dynamics access, you can grant permissions to other Microsoft services also and this credentials would work just okay with them also.
Phase 2 (Using the api) 
The first part is done, now to implement the actual API integration in nodejs we would be working with two libraries, 
Adal library for node , for active directory authentication Dynamics web api, An helper library for dynamics CRM
Install them like any other node module, follow the links above to learn more about these modules.
 I’d just put a copy of my code below, I won’t go into much details talking about the code as its very easy to follow. 
/*
* This service retrieves access token from 
* microsoft and then instantiates the dynamics web-api 
* service
*/

import * as adal from 'adal-node';
import * as DynamicsWebApi from "dynamics-web-api";


export class DynamicsConnector {
     authorityUrl: string;
     resource: string;
     clientId: string;
     username: string;
     password: string;
     adalContext: any;
     apiUrl: string;
     dynamicsWebApi : any;


    constructor(tenantId: string, resource: string, clientId: string, username: string, password: string){
        
        this.authorityUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/token`;
        this.resource = `https://${resource}/`;
        this.apiUrl   = resource;
        this.clientId = clientId;
        this.username = username;
        this.password = password;


            //create DynamicsWebApi object
            this.dynamicsWebApi = new DynamicsWebApi({
                webApiUrl: `https://${this.apiUrl}/api/data/v9.0/`,
                onTokenRefresh: this.acquireTokens
            });

        this.adalContext = new adal.AuthenticationContext(this.authorityUrl);

    }


    public acquireTokens = (dynamicsCallback: any) => {

        const adalCallback = (error:any, token:any) => {
    
            if (!error){
                //call DynamicsWebApi callback only when a token has been retrieved
                dynamicsCallback(token);
            }
            else{
                console.log('Token has not been retrieved. Error: ' + error.stack);
                }
        
        }
    
        this.adalContext.acquireTokenWithUsernamePassword(this.resource, this.username, this.password, this.clientId, adalCallback);
    }
    
    

     
   

}
The code sample consists of two typescript files, the first dynamics.service.ts and an app.ts file, the dynamics.service.ts is a service that handles the token retrieval from Active Directory using the adal module, and also initiates the Dynamics-web-api.
import { DynamicsConnector } from './dynamics.service';
//your tenant id obtained from Azure Active Directory
const dynamicsTenantId = "****************";

//CRM Organization URL
const dynamicsHost = '*******0.crm8.dynamics.com';

//Dynamics 365 Client Id  obtained from Azure active directory
const dynamicsClientId = '******************';

//your dynamics username
const dynamicsUserName = '***************';

//your dynamics password
const dynamicsPassword = '***********';

//instantiate the service
const dynamics = new DynamicsConnector(dynamicsTenantId,
                                        dynamicsHost,  
                                        dynamicsClientId,
                                        dynamicsUserName,
                                        dynamicsPassword).dynamicsWebApi;
                                    
  
//An Example from the dynamics web api docs
dynamics.retrieveMultiple("leads", ["fullname", "subject"], "statecode eq 0").then(function (records: any) {
    console.log(records)
})
.catch(function (error: any) {
    //catch an error
});
In the app.ts file we implement the DynamicsService by passing the required credentials to the constructor after which you can use the instance to run queries against your dynamics service. 
Follow this link to see the entities exposed by the dynamics api.
So that’s it for this post, I hope I have saved you a bit of time, if its been of any assistance to you, please show your appreciation by donating some claps.
O dabọ ✌️

Written by Dhemie | Devops and other drugs
Published by HackerNoon on 2019/10/22