Last week I wrote a post that showed how to update Dynamics 365 data from a Node.js application using the Web API. Today I will share equivalent Python code. This code builds on my Dynamics 365 and Python integration using the Web API post from last year, so if you haven't read that yet, please take a look before you proceed.
Updating a single property
To update a single property on a record in Dynamics 365, you can make a PUT request to the Web API. The raw HTTP request to update the first name for a contact would look like this:
PUT [Organization URI]/api/data/v8.2/contacts(00000000-0000-0000-0000-000000000001)/firstname HTTP/1.1
Content-Type: application/json
OData-MaxVersion: 4.0
OData-Version: 4.0
{"value": "Demo-Firstname"}
Assuming you have retrieved the OAuth token for authenticating to Dynamics 365 as I outlined in my earlier Python-Web API blog post, here is a sample Python function to make a PUT update request:
def updateContactPut(accesstoken, contactid):
crmrequestheaders = {
'Authorization': 'Bearer ' + accesstoken,
'Content-Type': 'application/json',
'OData-MaxVersion': '4.0',
'OData-Version': '4.0'
}
#make the crm request
contactObj={
'value':'Firstname PUT test'
};
crmres = requests.put(crmwebapi+'/contacts('+contactid+')/firstname', headers=crmrequestheaders, data=json.dumps(contactObj))
print(crmres)
Updating multiple properties
To update a multiple properties on a record in Dynamics 365, you must make a PATCH request to the Web API. The raw HTTP request to update the first name and last name for a contact would look like this:
PUT [Organization URI]/api/data/v8.2/contacts(00000000-0000-0000-0000-000000000001) HTTP/1.1
Content-Type: application/json
OData-MaxVersion: 4.0
OData-Version: 4.0
{
"firstname": "Demo-Firstname",
"lastname": "Demo-Lastname"
}
Again, assuming you have retrieved the OAuth token for authenticating to Dynamics 365 as I outlined in my earlier blog post, here is a sample Python function to make a PATCH update request:
def updateContactPatch(accesstoken, contactid):
crmrequestheaders = {
'Authorization': 'Bearer ' + accesstoken,
'Content-Type': 'application/json',
'OData-MaxVersion': '4.0',
'OData-Version': '4.0'
}
#make the crm request
contactObj={
'firstname':'Firstname test',
'lastname':'Lastname test'
};
crmres = requests.patch(crmwebapi+'/contacts('+contactid+')', headers=crmrequestheaders, data=json.dumps(contactObj))
print(crmres)
Further reading
For more information on updating and deleting data with the Dynamics 365 Web API, take a look at the "Update and delete entities using the Web API" article on MSDN.