Python – Accessing Microsoft GRAPH API

Python - Executing the Microsoft Graph API query - Fetching top 5 users
fig : Python - Executing the Microsoft Graph API query - Fetching top 5 users

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

fig 1 : Python - Downloading Python
fig : Python – Downloading Python
  • With following above articles I successfully installed Python on my local development environment
fig : Python - Python installed on my Windows 10 box successfully
fig : Python – Python installed on my Windows 10 box successfully
  • 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

fig : Python - Verifying Python version
fig : Python – Verifying Python version – Python installed successfully
  • Azure / Microsoft 365Register the application for user Authentication
fig : Azure Active Directory admin center - New app "Python Connector" created / registered successfully
fig : Azure Active Directory admin center – New app “Python Connector” created / registered successfully
fig : Azure Active Directory admin center - New app "Python Connector" details
fig : Azure Active Directory admin center – New app “Python Connector” details

Creating Python console application

  • Create new python file – Python_GraphAPI.py
  • Just use print() with any string to test as

print('LIFE IS BEAUTIFUL!')

fig : Python - Simple application to test whether Python code works
fig : Python – Simple application to test whether Python code works

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
fig : Azure Active Directory admin center - Creating new client secret key
fig : Azure Active Directory admin center – Creating new client secret key
  • 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

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

fig : Python - Getting access token
fig : Python – Getting access token
  • 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 –

fig : Python - Executing the Microsoft Graph API query
fig : Python – Executing the Microsoft Graph API query – Fetching top 5 users

Thanks for reading !!! Please feel free to discuss / suggestions / share thoughts !!!

HAVE A GREAT TIME AHEAD !!! LIFE IS BEAUTIFUL 🙂

Prasham Sabadra

LIFE IS VERY BEAUTIFUL :) ENJOY THE WHOLE JOURNEY :) Founder of Knowledge Junction and live-beautiful-life.com, Author, Learner, Passionate Techie, avid reader. Certified Professional Workshop Facilitator / Public Speaker. Scrum Foundation Professional certificated. Motivational, Behavioral , Technical speaker. Speaks in various events including SharePoint Saturdays, Boot camps, Collages / Schools, local chapter. Can reach me for Microsoft 365, Azure, DevOps, SharePoint, Teams, Power Platform, JavaScript.

You may also like...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: