The issue facing with the 401 error code likely stems from how you’re including the access token in your request to Dynamics CRM Web API. Here’s how to correctly use the access_token for your Python script using urllib2:

1. Use the correct resource URL

In your code, you’re requesting the access token with the resource set to “https://graph.microsoft.com“. However, Dynamics CRM Web API uses a different resource URL.
Update the resource parameter in your initial request to point to the Dynamics CRM Web API endpoint. You can find the specific URL for your organization by going to Settings -> Security -> Advanced Settings in Dynamics 365. Look for the Discovery Service Endpoint Url. This URL will typically look like https://your_organization.crm.dynamics.com/DiscoveryService.svc.

2. Include the access token in the Authorization header

You’ve got the structure mostly correct, but there’s a slight mistake. Change the way you add the Authorization header to:
Python
request.add_header(‘Authorization’, ‘Bearer {}’.format(access_token))
This ensures proper formatting for the Bearer token.

Here’s the revised code snippet for making the POST request:

Python
url = 'https://<company_uri>.dynamics.com/api/data/v8.1/leads'
post_fields = {"name": "Sample Account",
"creditonhold": "false",
"address1_latitude": 47.639583,
"description": "This is the description of the sample account",
"revenue": 5000000,
"accountcategorycode": 1
}

request = Request(url, urlencode(post_fields).encode())
request.add_header('Authorization', 'Bearer {}'.format(access_token))
request.add_header("Content-Type", "application/json; charset=utf-8")
request.add_header('OData-MaxVersion','4.0')
request.add_header('OData-Version','4.0')
request.add_header('Accept','application/json')
resp = urlopen(request).read().decode()

By making these changes, you should be sending the access token in the correct format and targeting the appropriate resource URL for Dynamics CRM Web API. This should hopefully resolve the 401 Unauthorized error.

Additional Tips

Double-check your access token for validity. Make sure it hasn’t expired.

Consider using a dedicated Dynamics CRM library like msdal for Python instead of urllib2. These libraries handle authentication and communication details more efficiently.

If you continue to face issues, refer to the official Microsoft documentation on Dynamics 365 Web API authentication.

Support On Demand!

QA Automation