Upload File(s) into Sharepoint/Office365 using Azure Graph API and Python
- Sumit Dey
- Feb 9, 2022
- 2 min read
Updated: Feb 24, 2022
This post is specially designed for uploading the file(s) into the SharePoint document library using Graph API and Python. Here is the proposed architecture

There is no clear documentation from Microsoft to upload documents into Sharepoint sites using python script. Here are steps for uploading documents into the Sharepoint site
1) Register app in Azure Portal
a) First, need to register the app in Azure Portal.

b) While creating the app, please copy the client id and secret for future reference.
c) Please configure the implicit grant and hybrid flows

d) Please provide API permission for files.Readwrite.All and sites.ReadWrite.All


e) Define the scope of the API

f) In the Manifest file, please make sure the following configuration would be true

2) Python script with Graph API to upload files into Sharepoint site.
a) Install Python package Frist needs to install Microsoft Authentication Library (MSAL) for Python
pip install msal
b) Find out site Id and Document Library ID using Graph explorer
Get site ID using Graph explorer and query the following URL(GET method)
https://graph.microsoft.com/v1.0/sites/<tenant name>.sharepoint.com:/sites/<Site Name> i.e. https://graph.microsoft.com/v1.0/sites/sss.sharepoint.com:/sites/pythonsite

Get Sharepoint Document Library ID using Graph explorer and query the following URL(GET method)
https://graph.microsoft.com/v1.0/sites/<site id>/drives
site id - Please use the site id from the previous query

c) Get the access token using the client id, client secret, and tenant id
Here is the python code to get access token import msal
import json
import requests
import os
client_id = '<client id>'
client_secret = '<Client Secret>'
tenant_id = '<Tenant id>'
authority = f"https://login.microsoftonline.com/{tenant_id}"
app = msal.ConfidentialClientApplication(
client_id=client_id,
client_credential=client_secret,
authority=authority)
scopes = ["https://graph.microsoft.com/.default"]
result = None
result = app.acquire_token_silent(scopes, account=None)
if not result: # No access token exists
print(
"No suitable token exists in cache. Let's get a new one from Azure Active
Directory.")
result = app.acquire_token_for_client(scopes=scopes)
if "access_token" in result: # access token exists
print("Access token is " + result["access_token"])
d) Upload files into Sharepoint server
There are two processes to upload files into Sharepoint sites, according to the Microsoft documentation, need to create a session if the file is more than 4MB. i) Upto 4MB file
filename = 'TestUpload.docx'
filepath = '/python/'
file_size = os.path.getsize(filepath+filename)
if (file_size <= 4194304): # Less than 4 MB file
endpoint = f'https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{list_id}/root:/{filename}:/content'
data = open(filepath+filename, 'rb').read()
requests.put(endpoint, data=data,
headers={'Authorization': 'Bearer ' + result['access_token'],
'Content-Type':'application/binary'},)
else: # More than 4 MB file
endpoint = f'https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{list_id}/root:/{filename}:/createUploadSession'
graph_data = requests.post(endpoint,
headers={'Authorization': 'Bearer ' + result['access_token']},).json()
print("Upload URL: %s" % graph_data['uploadUrl'])
data = open(filepath+filename, 'rb').read()
content_range = 'bytes 0-'+str(file_size-1)+'/'+ str(file_size)
f_data = requests.put(graph_data['uploadUrl'], data=data,
headers={'Authorization': 'Bearer ' + result['access_token'],
'Content-Range': content_range,
'Content-Type':'application/binary'},).json()
e) Update Metadata
# Update Metadata
requestURL = f'https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{list_id}/root:/{filename}:/listItem/fields'
metadata = {
"Title": "Test Title",
"DocumentType": "Word Document" # Custom metadata
}
jsondata = json.dumps(metadata)
graph_data_metadata = requests.patch(requestURL, data=jsondata,
headers={'Authorization': 'Bearer ' + result['access_token'],
'Content-Type':'application/json'},).json()
Please email(sumitdeyonline@gmail.com) me if you have any issues or concerns.
Commentaires