Below is how I authenticate and call Microsoft Graph API to work with SharePoint from Python application.
Plain
no MSAL or Azure libraries used:
import requests
import json
from secrets import clientSc
clientId = "7e60c372-ec15-4069-a4df-0ab47912da46"
# clientSc = "<imported>"
tenantId = "7ddc7314-9f01-45d5-b012-71665bb1c544"
apiUri = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token"
body = {
"client_id" : clientId,
"client_secret" : clientSc,
"scope" : "https://graph.microsoft.com/.default",
"grant_type" : "client_credentials"
}
response = requests.post(apiUri, data=body)
token = json.loads(response.content)["access_token"]
graph_url = 'https://graph.microsoft.com/v1.0/sites/root'
site = requests.get(
graph_url,
headers={'Authorization': 'Bearer {0}'.format(token)}
)
print(site.content)
print(json.loads(site.content)["webUrl"])
secrets is a Python file where I assign client secret to variable clientSc (so my secret is not shared on github). This is ok for demo purposes but generally, you should not hard-code secrets but keep secrets somewhere safe (Vault).
MSAL
Using MSAL library to get bearer token:
https://github.com/VladilenK/m365-with-Python/tree/main/Graph-API-MSAL
References
- Github repo: https://github.com/VladilenK/m365-with-Python