Integrate Microsoft Dynamics 365 CE with Python 3.6

Hello and Welcome!

Today we will see how we can integrated Microsoft Dynamics 365, Customer Engagement with Python using Odata Web API.

Python is very powerful and so its use for modern application is irreplaceable, Be it Web App, Mobile App, Desktop App or Any Machine learning project as a whole.
Lets get started.

Basically, Requirement for this is when we do integration with Dynamics 365 CRM.
We have native application already and we want to pull data from MS CRM or push data in MS CRM.

i found following two way the better option for integration application

1. Where we do not need to provide User’s credentials and records can be created on behalf of application
2. Where we do have to pass Client credentials, but this is when you want to integrate for Specific Application with Specific User.

Before we begin to code, We have to register our Dynamics App in Azure to get Client Id and Client Secret.
Please visit my blog here to get following details

Client ID
Client Secret
Call back URL
Resource URL
Auth URL
Token URL.

Once you have above Details, it just following few lines of code which will help you connect Microsoft Dynamics CRM.

Approach 1 : where we don’t need user credentials, we can just use Client ID and Client Secret.

# !pip install adal , If Required
import adal
import requests
import json

# Global configs.
CLIENT_ID = '6663dac9-e6bf-4340-949d-dda260a65d27'
RESOURCE_URI = 'https://orgname.crm8.dynamics.com'
AUTHORITY_URI = 'https://login.microsoftonline.com/ab758891-bfde-44ba-8f4d-49ed229d9156'
CLIENT_SECRET = 'XdTCbd_hHc0MQAYeGL6d16-y---3D4d_5e'
ENTITY = 'contact'

# Get an access token.
context = adal.AuthenticationContext(AUTHORITY_URI, api_version=None)
token = context.acquire_token_with_client_credentials(RESOURCE_URI, CLIENT_ID, CLIENT_SECRET)
session = requests.Session()
session.headers.update(dict(Authorization='Bearer {}'.format(token.get('accessToken'))))

# Request image.
request_uri = 'https://orgname.api.crm8.dynamics.com/api/data/v8.2/contacts?$select=fullname,contactid'
r = session.get(request_uri)
rawJson = r.content.decode('utf-8')
print(rawJson)

Response

{
  "@odata.context": "https://orgurl.api.crm8.dynamics.com/api/data/v8.2/$metadata#contacts(fullname,contactid)",
  "value": [
    {
      "@odata.etag": "W/\"6643408\"",
      "fullname": "MyAnalytics",
      "contactid": "204670ae-72cd-ea11-a812-000d3af0543f"
    },
    {
      "@odata.etag": "W/\"6643460\"",
      "fullname": "Office365 Message Center",
      "contactid": "c53e76b4-72cd-ea11-a812-000d3af0543f"
    },
    {
      "@odata.etag": "W/\"6643482\"",
      "fullname": "Microsoft Power Automate",
      "contactid": "db3e76b4-72cd-ea11-a812-000d3af0543f"
    },
    {
      "@odata.etag": "W/\"6645158\"",
      "fullname": "Kalyan P Reddy",
      "contactid": "43d975c0-72cd-ea11-a812-000d3af0543f"
    },
    {
      "@odata.etag": "W/\"6645291\"",
      "fullname": "Azure DevOps",
      "contactid": "fe9e77c6-72cd-ea11-a812-000d3af0543f"
    },
    {
      "@odata.etag": "W/\"6645919\"",
      "fullname": "Sudeep Satpathy",
      "contactid": "c78204b2-76cd-ea11-a812-000d3af0543f"
    },
    {
      "@odata.etag": "W/\"6645947\"",
      "fullname": "Avani Arora",
      "contactid": "de8204b2-76cd-ea11-a812-000d3af0543f"
    },
    {
      "@odata.etag": "W/\"6638013\"",
      "fullname": "Sudeep Satpathy",
      "contactid": "92e0b7d6-04cd-ea11-a812-000d3af05a1b"
    },
    {
      "@odata.etag": "W/\"6638186\"",
      "fullname": "Sudeep Satpathy",
      "contactid": "e1c9f967-08cd-ea11-a812-000d3af05a1b"
    },
    {
      "@odata.etag": "W/\"6319460\"",
      "fullname": "Test 1 1",
      "contactid": "36146846-22c7-ea11-a812-000d3af05a4b"
    },
    {
      "@odata.etag": "W/\"6641557\"",
      "fullname": "Avani Arora",
      "contactid": "b8252d00-2dcd-ea11-a812-000d3af05a4b"
    },
    {
      "@odata.etag": "W/\"6649383\"",
      "fullname": null,
      "contactid": "3a37ee11-d1ad-40b0-890b-21fd3e30d448"
    }
  ]
}

Approach 2 : where we will need to use user credentials with Client ID and Client Secret.

import requests
import json
 
crmorg = 'https://orgurl.crm8.dynamics.com' #base url for crm org
clientid = '6663dac9-e6bf-4340-949d-dda260a65d27' #application client id
username = 'userid@domain.onmicrosoft.com' #username
userpassword = 'password' #password
tokenendpoint = 'https://login.microsoftonline.com/ab758891-bfde-44ba-8f4d-49ed229d9156/oauth2/token' #oauth token endpoint
 
#set these values to query your crm data
crmwebapi = 'https://orgname.api.crm8.dynamics.com/api/data/v8.2' #full path to web api endpoint
crmwebapiquery = '/contacts?$select=fullname,contactid' #web api query (include leading /)
 
tokenpost = {
    'client_id':clientid,
    'resource':crmorg,
    'username':username,
    'password':userpassword,
    'grant_type':'password'
}
 
#make the token request
tokenres = requests.post(tokenendpoint, data=tokenpost)
 
#set accesstoken variable to empty string
accesstoken = ''
 
#extract the access token
try:
    accesstoken = tokenres.json()['access_token']
except(KeyError):
    #handle any missing key errors
    print('Could not get access token')

#if we have an accesstoken
if(accesstoken!=''):
    #prepare the crm request headers
    crmrequestheaders = {
        'Authorization': 'Bearer ' + accesstoken,
        'OData-MaxVersion': '4.0',
        'OData-Version': '4.0',
        'Accept': 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        'Prefer': 'odata.maxpagesize=500',
        'Prefer': 'odata.include-annotations=OData.Community.Display.V1.FormattedValue'
    }
 
    #make the crm request
    crmres = requests.get(crmwebapi+crmwebapiquery, headers=crmrequestheaders)
 
    try:
        #get the response json
        crmresults = crmres.json()
        print(crmresults)
    except KeyError:
        #handle any missing key errors
        print('Could not parse CRM results')

Response

{
   "@odata.context":"https://orgurl.api.crm8.dynamics.com/api/data/v8.2/$metadata#contacts(fullname,contactid)",
   "value":[
      {
         "@odata.etag":"W/\"6643408\"",
         "fullname":"MyAnalytics",
         "contactid":"204670ae-72cd-ea11-a812-000d3af0543f"
      }
   ]
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s