Python – Accessing Microsoft GRAPH API

Hi All,
Greetings for the day!!!
Today bit new topic.
Background :
- Since in my organization one of developer have an issue while accessing Microsoft GRAPH API from his Python application
- This query came to me and hence POC and birth of this article 🙂
In this article we will discuss how to access Microsoft Graph APIs from Python application. I am using Windows 10 on my local development environment
Prerequisites
- Python
- We need to have Python installed on our development environment
- We can download Python and install from official Python site – https://www.python.org/
- If you don’t know much about Python and want to know more in depth, please have a look our detailed articles on Python – https://knowledge-junction.in/category/python/
- Introduction to Python – https://knowledge-junction.in/2021/08/27/introduction-to-python/
- Installing Python – https://knowledge-junction.in/2019/07/04/python-for-beginners-part-2-installing-python/
- With following above articles I successfully installed Python on my local development environment
- We could also verify by running version CMDLET
- I am using Visual Studio code
- We could check Python version by CMDLET – Python -V
- This CMDLET also ensures that Python is installed successfully
Python -V
- Azure / Microsoft 365 – Register the application for user Authentication
- We need to register application in Azure Active Directory admin center (AAD admin center)
- We have detailed article for registering application in AAD admin center – Office 365 – Azure Active Directory – Registering/Creating new Azure App – detailed steps
- With the steps following in above article I created / registered new application “Python Connector” on my local tenant AAD admin center as shown in below fig

Creating Python console application
- Create new python file – Python_GraphAPI.py
- Just use print() with any string to test as
print('LIFE IS BEAUTIFUL!')
Creating client secret key for our app
- If you still didn’t created client secret key, please generate the client secret key
- We could create client secret key by navigating to “Our app >> Manage >> Certificates & secrets ” in Azure AD admin center
- Important Point – Once new client secret key is generated, make sure we are copying it. Since once we moved from the respective page we can not get the client secret key. Only option have is to create new client secret key.
Once we have these prerequisites in place we are ready for next step – Getting Access token.
Since Microsoft GRAPH APIs are secured APIs we need access token to use them
Access Token :
- What is Access Token? – Access Token is 64-bit encoded JSON Web Token (JWT)
- Example:
EwAoA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAXu71AU9f4aS4rOK5xoO/SU5HZKSXtCsDe0Pj7uSc5Ug008qTI+a9M1tBeKoTs7tHzhJNSKgk7pm5e8d3oGWXX5shyOG3cKSqgfwuNDnmmPDNDivwmi9kmKqWIC9OQRf8InpYXH7NdUYNwN+jljffvNTewdZz42VPrvqoMH7hSxiG7A1h8leOv4F3Ek/oeJX6U8nnL9nJ5pHLVuPWD0aNnTPTJD8Y4oQTp5zLhDIIfaJCaGcQperULVF7K6yX8MhHxIBwek418rKIp11om0SWBXOYSGOM0rNNN59qNiKwLNK+MPUf7ObcRBN5I5vg8jB7IMoz66jrNmT2uiWCyI8MmYDZgAACPoaZ9REyqke+AE1/x1ZX0w7OamUexKF8YGZiw+cDpT/BP1GsONnwI4a8M7HsBtDgZPRd6/Hfqlq3HE2xLuhYX8bAc1MUr0gP9KuH6HDQNlIV4KaRZWxyRo1wmKHOF5G5wTHrtxg8tnXylMc1PKOtaXIU4JJZ1l4x/7FwhPmg9M86PBPWr5zwUj2CVXC7wWlL/6M89Mlh8yXESMO3AIuAmEMKjqauPrgi9hAdI2oqnLZWCRL9gcHBida1y0DTXQhcwMv1ORrk65VFHtVgYAegrxu3NDoJiDyVaPZxDwTYRGjPII3va8GALAMVy5xou2ikzRvJjW7Gm3XoaqJCTCExN4m5i/Dqc81Gr4uT7OaeypYTUjnwCh7aMhsOTDJehefzjXhlkn//2eik+NivKx/BTJBEdT6MR97Wh/ns/VcK7QTmbjwbU2cwLngT7Ylq+uzhx54R9JMaSLhnw+/nIrcVkG77Hi3neShKeZmnl5DC9PuwIbtNvVge3Q+V0ws2zsL3z7ndz4tTMYFdvR/XbrnbEErTDLWrV6Lc3JHQMs0bYUyTBg5dThwCiuZ1evaT6BlMMLuSCVxdBGzXTBcvGwihFzZbyNoX+52DS5x+RbIEvd6KWOpQ6Ni+1GAawHDdNUiQTQFXRxLSHfc9fh7hE4qcD7PqHGsykYj7A0XqHCjbKKgWSkcAg==
- Access token contains information about
- our app (claim).
- Permission app has for the resource (Microsoft cloud service => Office 365 Groups, Users, Mail, contact etc.) – ensures that caller has proper permissions
- It contains information about API available through Microsoft Graph
Steps to get the Access Token in Python code
- To call Microsoft Graph, our app must acquire an access token from Azure Active Directory (AD), Microsoft cloud identity service
- Our app need to be able to authenticate with Azure AD
- We attach the access token as a Bearer token to the Authorization header in our HTTP requests
- To get access token we need following details
- client id / appid
- client secret key
- tenant id
- token URL / Login URL – https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/token
- scope – https://graph.microsoft.com/.default
LOGIN_URI = f'https://login.microsoftonline.com/6b38e1c3-a1fe-40cc-8b93-a4159a50592c/oauth2/v2.0/token'
headers = {
'Host': 'login.microsoftonline.com',
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'client_id': '9c9fed7a-9be2-41f3-a7fa-972b4588ccc4',
'scope': 'https://graph.microsoft.com/.default',
'client_secret': '<client secret key goes here>',
'grant_type': 'client_credentials',
'tenant': '6b38e1c3-a1fe-40cc-8b93-a4159a50592c'
}
response = post(url=LOGIN_URI, headers=headers, data=body)
response.raise_for_status()
response_body = response.json()
authorization_token = f"{response_body['token_type']}
{response_body['access_token']}"
access_token = 'Bearer ' + response_body['access_token']
print(access_token)
- Add above code in our “Python_GraphAPI.py” python file
- Run the code
python Python_GraphAPI.py
and output will be

- Once we have access token we are ready to query to Microsoft 365 or ready to execute the SharePoint REST APIs
- Lets get the few users available in our Tenant
- We need to pass the authentication token which we received
- Following is the code
#adding authentication token to our Microsoft365 requests
headers={
"Authorization": access_token
}
#getting first 5 users
result = requests.get(f'https://graph.microsoft.com/v1.0/users?$top=5', headers=headers)
result.raise_for_status()
print(result.json())
and output will be –
Thanks for reading !!! Please feel free to discuss / suggestions / share thoughts !!!
HAVE A GREAT TIME AHEAD !!! LIFE IS BEAUTIFUL 🙂
You must log in to post a comment.