Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Python App to query on D365 API with app id / app key returns 401 error

Posted on by Microsoft Employee

Hello,

I've got an issue with a small script I'm trying to run to query the API with a python script.

I've registered the app on Azure, gives the permission, created an application user, assigned him a clone of the admin rights but I always get a 401 error returned.. no idea why..

Here is my code:

context = adal.AuthenticationContext('login.microsoftonline.com'+ directoryid)
tokenresponse = context.acquire_token_with_client_credentials('orgname.crm4.dynamics.com', appid, appkey)
print(tokenresponse)
accesstoken = tokenresponse.get('accessToken')
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'
}

crmres = requests.get(crmwebapi+ "/accounts?$select=accountid&$filter=name eq '000'", headers=crmrequestheaders)

I then get a 401 error returned while I get a 'valid' token returned... this is very weird..

ANyone had the same issue?

Thanks

*This post is locked for comments

  • Suggested answer
    nnichols Profile Picture
    nnichols 10 on at
    RE: Python App to query on D365 API with app id / app key returns 401 error

    Hi Bipin,

    Thanks for the response. I figured this out over the weekend and indeed it was a permissions issue. For some reason the custom security role I created that allowed Licensed Users to have CRUD permissions on entities in my app would not allow the same actions through the API with an Application User.

    I found that the default role of 'System Customizer' had the sufficient permissions for my use case, which was to download a binary image from the Image field type on a custom Entity. 

    Here is an example script of how I was able to do this:

    import adal
    import requests
    
    # Global configs.
    CLIENT_ID = ''
    RESOURCE_URI = 'https://.crm.dynamics.com'
    AUTHORITY_URI = 'https://login.microsoftonline.com/'
    CLIENT_SECRET = 'AZURE-APP-SECRET>
    ENTITY = '1234-5678-9101-1123'
    
    # 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 = f'{RESOURCE_URI}/api/data/v9.0/cr711_my({ENTITY})/cr711_image/$value?size=full'
    r = session.get(request_uri)
    with open('image.png', 'w b') as fi:
        fi.write(r.content)

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Python App to query on D365 API with app id / app key returns 401 error

    HI,

    Can you try assigning OOB system admin role and then check if it working fine ?

  • nnichols Profile Picture
    nnichols 10 on at
    RE: Python App to query on D365 API with app id / app key returns 401 error

    Likewise, same issue here...

  • An.NING Profile Picture
    An.NING 5 on at
    RE: Python App to query on D365 API with app id / app key returns 401 error

    Have you solved the problem at last? I had the same problem

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Python App to query on D365 API with app id / app key returns 401 error

    I see as well that the error returned is the following:

    "Principal user (Id=64936d46-f146-e811-a970-000d3ab382ec, type=8) is missing prvReadContact privilege (Id=ba09ec92-12c4-4312-ba16-5715c2cbd6da)"

    The id of the principal user is indeed the application user I created. Nevertheless, I gave that user, a custom clone role of the system admin role :s any ideas?

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Python App to query on D365 API with app id / app key returns 401 error

    Even following this tutorial: phuocle.net/.../dynamics-365-online-s2s-authentication-full-explain.aspx

    I am still getting 401 error..

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans