Connect to SharePoint Online from Python
SharePoint Online is free included feature for Microsoft 365. Since it is a free and very feasible platform, we use SharePoint Online (SPO) to store many business data. It would be very helpful to connect your programming platform to SPO. I use Python in my case. In order to let your Python code successfully authenticated, we will use Azure App Registration feature.
Reg the App
First we need to register our App to Azure and grant sufficient permission to the App so that it can manage SharePoint. You need to have Global Admin permission to run below cmdlet. To save you from a lot of trouble, you should install PnP module.
In PowerShell prompt, run:
Install-Module PnP.PowerShell
Then run:
Register-PnPManagementShellAccess
Finally:
$app = Register-PnPAzureADApp -ApplicationName “Here the name of your application” -Store CurrentUser -Tenant yourtenant.onmicrosoft.com -Username “your-username” -Password (Read-Host -AsSecureString -Prompt “Enter Password”) -CertificatePassword (Read-Host -AsSecureString -Prompt “Enter Certificate Password”) -OutPath .\
$app.’AzureAppId/ClientId’
$app.’Certificate Thumbprint’
After input above cmdlet, you will be prompted to input (1) the global admin’s entra ID password; (2)The certificate’s password. You can type in any string as password but please copy it down for later step.
After the cmdlet finish run, open Azure portal. Search for “App registrations” and click on it. In the list of “Owned Application” you will find your registered App there. Open the app, and then click on “API Permission” at left navigation, you will find all the granted permission for this App.
There are 2 approaches to authenticate your code with this App.
— Client ID and secret pair
— Certificate
The client ID and secret is no longer supported. It will be fully retired after 2026. In our case, certificate is used. A X.509 certificate is generated and upload to Azure when we run the Register-PnPAzureADApp cmdlet.
You will also find 2 physical cert files (one in .PFX and another in .CER format) under “-OutPath” which is the running path of the cmdlet. Make a backup of them.
In the PowerShell output screen, you will find the App’s ClientId and Certificate Thumbprint. Make a copy of them as well.
Convert certificate to plain text
We need to convert the pfx file into pem format. Then you can open it with notepad and it is readable to human eye. I use PSPKI to do it.
To install, run below in PowerShell:
Install-Module -Name PSPKI
After install the module, run below cmdlet for conversion:
Convert-PfxToPem -InputFile ‘C:\yourfolder\YourAppName.pfx’ -Password $password -OutputFile ‘C:\yourfolder\YourAppName.pem’
You need to use the certificate password you copied down from previous section.
Finally, open the PEM file with notepad. Copy all the content and paste in the sample code in next section.
Programming
It is time to do some programming. We will use Office365-REST-Python-Client library. Please visit their Github to learn about the installation steps. After install and setup the library in your programming environment, use below code to connect to SharePoint.
from office365.runtime.auth.token_response import TokenResponse
from office365.sharepoint.client_context import ClientContext
cert_pem_content = “”” — — -BEGIN CERTIFICATE — — -
— — -END CERTIFICATE — — -
— — -BEGIN PRIVATE KEY — — -
— — -END PRIVATE KEY — — -
“””
def acquire_token():
cert_settings = {
‘tenant’: “yourtenant.onmicrosoft.com”,
‘client_id’: ‘yourClientId’,
‘thumbprint’: “your”,
‘resource’: ‘https://yourtenant.sharepoint.com’,
‘private_key’: cert_pem_content
}
authority_url = ‘https://login.microsoftonline.com/{0}'.format(cert_settings.get('tenant'))
credentials = {
“thumbprint”: cert_settings.get(‘thumbprint’),
“private_key”: cert_pem_content
}
scopes = [“{url}/.default”.format(url=cert_settings.get(‘resource’))]
import msal
app = msal.ConfidentialClientApplication(
cert_settings.get(‘client_id’),
authority=authority_url,
client_credential=credentials,
)
result = app.acquire_token_for_client(scopes)
return TokenResponse.from_json(result)
site_url = “https://yourtenant.sharepoint.com/"
ctx = ClientContext(site_url).with_access_token(acquire_token)
current_web = ctx.web.get().execute_query()
print(“{0}”.format(current_web.url))
Here you’re. Hope it works for you!