Spaces:
Sleeping
Tutorial on Setting up MS Graph API
This is a short tutorial for how to Integrate MS Graph API with your python app.
We will cover..
- Azure Web App Registration calling redirect URL
- Enable Scope of MS Graph API Permissions for Services you want.
- Install Azure Python client package
- Auth with authorization code, login not required, for personal use.
- Auth with prompt login.
1. Create an Azure App Registration for Web.
for localhost 8000 port and callback method
2. Python in VSCode or Huggingface streamlit app for simplicity:
New streamlit app on Huggingface, then new file App.py
Contents:
APPLICATION_ID=''
CLIENT_SECRET=''
3. Get the Azure Application Client ID from the App Reg:
Application Client ID is what you need. Copy and Paste into APPLICATION_ID in py code.
4. Create an Azure secret in MS Graph API Certificates and Secrets
5. Copy Azure Value for MSGraphAPI into CLIENT_SECRET py
In Huggingface and Docker you will want to feature your keys outside of the app.py. To do this on Huggingface add both Application ID and and Client secret into Space Secrets which are stored securely in github as secrets, then access them like this:
HF_KEY = os.getenv('HF_KEY')
SO we now will have the first two lines of python to access MS Graph API:
APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')
These will read the Secrets from the Space when it starts up and add them to environment variables for access by py code:
6. Use Graph Explorer to Test out the API for MS Graph API
https://developer.microsoft.com/en-us/graph/graph-explorer
Log into a MS account that has an Email associated to it. I will use mine [email protected]
7. Test the graph endpoint. Also Determine which endpoints you will want to use.
https://graph.microsoft.com/v1.0/me
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
"@microsoft.graph.tips": "Use $select to choose only the properties your app needs, as this can lead to performance improvements. For example: GET me?$select=signInActivity,accountEnabled",
"userPrincipalName": "[email protected]",
"id": "283fb506ed9f3ddf",
"displayName": "Aaron Wacker",
"surname": "Wacker",
"givenName": "Aaron",
"preferredLanguage": "en-US",
"mail": null,
"mobilePhone": null,
"jobTitle": null,
"officeLocation": null,
"businessPhones": []
}
8. Selecting MS Graph Endpoints:
There are the following main options. In β the main ones we will use for email and scheduling.
Main MSGraph Options
- π Contact -------------- β
- π Files
- π₯ Groups
- π€ Users
- π§βπ€βπ§ Teams
- π± Devices
- π Meetings -------------- β
- βοΈ Settings
- βοΈ Mail -------------- β
- π‘οΈ Security -------------- β
- π Access -------------- β
- ποΈ Calendar -------------- β
- π Insights
9. Set Scope of API permissions
Add a permission
Choose Microsoft Graph, Delegated permissions
To keep things simple first pass through choose my profile endpoint which is shown above (me)
10. Create requirements.txt for python libraries to pull in.
For any python libraries you use pip install -r requirements.txt is used to install all libraries with compatible versions.
You can also use search to review the pypi page for any given python library. This is a great way to get the context and review documentation and code samples for usage of any python library.
For AI Pair Programming a Pro Skill is to be able to copy the appropriate code samples into an AI pipeline (GPT or Claude recommended due to coding python accuracy).
Create requirements.txt in HF by File, New File then enter msal library and commit:
You will then have two files in your project:
app.py
import msal
from msal import PublicClientApplication
APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')
requirements.txt
msal
11. Set your graph URL
base_url = 'https://graph.microsoft.com/v1.0/'
endpoint = base_url + 'me'
12. Request API Permissions to create Scope:
SCOPES = ['User.Read','User.Export.All']
13. Add authority URL used to authenticate:
authority_url = 'https://login.microsoftonline.com/consumers'
14. add client instance method call on msal:
import msal
from msal import PublicClientApplication
APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')
authority_url = 'https://login.microsoftonline.com/consumers'
base_url = 'https://graph.microsoft.com/v1.0/'
endpoint = base_url + 'me'
SCOPES = ['User.Read','User.Export.All']
# Authenticate with Auth Code
client_instance = msal.ConfidentialClientApplication(client_id=APPLICATION_ID_KEY, client_credential=CLIENT_SECRET_KEY, authority_url=authority_url )
#15. Get your token from Azure platform - Graph Explorer, Service of User/me and then Access token:
16. From MS Graph we also need the Response headers
{
"client-request-id": "72fdf4e2-0ab3-a835-abf6-bbe03077181f",
"content-type": "application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8",
"request-id": "5ed61711-f89b-460b-8816-cc0a71181fb3"
}
- Use client_instance.get_authorization_request_url
Code should be as follows:
import msal
import os
import streamlit as st
from msal import PublicClientApplication
APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')
authority_url = 'https://login.microsoftonline.com/consumers'
base_url = 'https://graph.microsoft.com/v1.0/'
endpoint = base_url + 'me'
SCOPES = ['User.Read','User.Export.All']
# Authenticate with Auth Code
client_instance = msal.ConfidentialClientApplication(
client_id=APPLICATION_ID_KEY, client_credential=CLIENT_SECRET_KEY, authority=authority_url
)
authorization_request_url = client_instance.get_authorization_request_url(SCOPES)
st.write('Connecting to MSGraph with url:' + authorization_request_url)
webbrowser.open(authorization_request_url, new=True)
- Add webbrowser call:
import msal
import os
import streamlit as st
import webbrowser
from msal import PublicClientApplication
APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')
authority_url = 'https://login.microsoftonline.com/consumers'
base_url = 'https://graph.microsoft.com/v1.0/'
endpoint = base_url + 'me'
SCOPES = ['User.Read','User.Export.All']
# Authenticate with Auth Code
client_instance = msal.ConfidentialClientApplication(
client_id=APPLICATION_ID_KEY, client_credential=CLIENT_SECRET_KEY, authority=authority_url
)
authorization_request_url = client_instance.get_authorization_request_url(SCOPES)
st.write('Connecting to MSGraph with url:' + authorization_request_url)
webbrowser.open(authorization_request_url, new=True)
- Since we configured to debug locally when we deploy to HF we need to update the Redirect URI in Azure App Registration.
After entering your deploy URL that you run your app from, delete the localhost entry: