Reputation: 343
I am trying to add a new application role to Azure AD users via Graph API using Python. But I face issue. I follow the Microsoft docs: https://learn.microsoft.com/en-us/graph/api/user-post-approleassignments?view=graph-rest-1.0&tabs=http
the structure works properly when using Postman. Below is the Python script:
import json, requests
def test():
token={ACCESS_TOCKEN}
data={"principalId":"ff868303-fbb7-4027-87a1-00b92013d343","resourceId":"4f162966-2c98-4439-b924-7730c40e98551","appRoleId":"827ee854-4907-4e96-b238-c861d846c450"}
return requests.post('https://graph.microsoft.com/v1.0/Users/ff868303-fbb7-4027-87a1-00b92013d343/appRoleAssignments',
headers={'Authorization': 'Bearer ' + token_request , 'Content-Type': "application/json"},
data=data
)
The error:
{'error': {'code': 'BadRequest', 'message': 'Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.', 'innerError': {'date': '2020-11-25T15:43:24', 'request-id':
'8301f593-cab8-4228-b053-c9d24139a85f', 'client-request-id': '8301f593-cab8-4228-b053-c9d24139a85f'}}}
Upvotes: 0
Views: 645
Reputation: 6508
Because you are not posting a json to the REST API. Use 'json' argument instead of 'data' of post method. Refer https://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests. Should be:
import json, requests
from uuid import UUID
def test():
token={ACCESS_TOCKEN}
data={"principalId":UUID("ff868303-fbb7-4027-87a1-00b92013d343"),"resourceId":UUID("4f162966-2c98-4439-b924-7730c40e98551"),"appRoleId":UUID("827ee854-4907-4e96-b238-c861d846c450")}
return requests.post('https://graph.microsoft.com/v1.0/Users/ff868303-fbb7-4027-87a1-00b92013d343/appRoleAssignments',
headers={'Authorization': 'Bearer ' + token, 'Content-Type': "application/json"},
json = data
)
Or, you can also dump json from the dictionary and pass in the data argument. data = json.dumps(data)
.
Upvotes: 1