Dynamics 365 and Python integration using the Web API

A few days back I wrote a post that showed an easy way to set up Dynamics 365 and Node.js integration using the Web API. Here is Python code that demonstrates equivalent functionality to query contacts and display their information:

import requests  
import json

#set these values to retrieve the oauth token
crmorg = 'https://CRMORG.crm.dynamics.com' #base url for crm org  
clientid = '00000000-0000-0000-0000-000000000000' #application client id  
username = 'xxxxxx@xxxxxxxx' #username  
userpassword = 'xxxxxxxx' #password  
tokenendpoint = 'https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/token' #oauth token endpoint

#set these values to query your crm data
crmwebapi = 'https://CRMORG.api.crm.dynamics.com/api/data/v8.2' #full path to web api endpoint  
crmwebapiquery = '/contacts?$select=fullname,contactid' #web api query (include leading /)

#build the authorization token request
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()

        #loop through it
        for x in crmresults['value']:
            print (x['fullname'] + ' - ' + x['contactid'])
    except KeyError:
        #handle any missing key errors
        print('Could not parse CRM results')

This assumes you have configured an application in Azure Active Directory and know its client id and the Azure AD tenant id just like in my earlier Node.js example.

When I run this from my local PC against a my Dynamics 365 org with sample data installed, I get this output:
Python shell output

Like my earlier Node.js example, this Python version isn't fancy, but it shows how easy it is to authenticate to Dynamics 365 and retrieve data without requiring special libraries.

comments powered by Disqus