Get SharePoint Online Access Token Using Python

Introduction

SharePoint Online access token is required to perform any CRUD operations.

Before using this code, please make sure that your SharePoint app is registered and installed in your target Site Collection, and you should have the below details

  1. SharePoint App Client ID
  2. SharePoint App Client Secret
  3. SharePoint Tenant ID
  4. SharePoint Site Hostname

Get SharePoint Online Access Token

Here is the code using which you can acquire the SharePoint Online Access token.

import requests
import urllib

def get_sharepoint_access_token(clientId,clientSecret,hostName,tenantId):
    # Auth URL
    auth_url = "https://accounts.accesscontrol.windows.net/vodafone.onmicrosoft.com/tokens/OAuth/2"
    
    # Encode the client secret 
    client_secret = urllib.parse.quote(clientSecret)
    #print(client_secret)

    _headers = {'Content-type': 'application/x-www-form-urlencoded'}
    _data = f'grant_type=client_credentials&resource=00000003-0000-0ff1-ce00-000000000000/{hostName}@{tenantId}&client_id={clientId}@{tenantId}&client_secret={client_secret}'
    #print(_data)
    auth_response = requests.post(
      auth_url, 
      headers=_headers,
      data=_data
    )
    
    #print(auth_response)
    #print(auth_response.text)
    #print(auth_response.json()["access_token"])
    
    return auth_response.json()["access_token"]
    

# SharePoint App Id
client_id = "<SharePoint App ID/ClientID>"
# SharePoint All Secret
client_secret = "<SharePoint App Secret/ClientSecret>"
# Root Site Host Name
sharepoint_host_name = "mysite.sharepoint.com"
# SharePoint Tenant Id
tenant_id = "<SharePoint Tenant ID>"

# Get the access token 
access_token = get_sharepoint_access_token(client_id,client_secret,sharepoint_host_name,tenant_id)

# Access Token  
print(f"SharePoint Access token --> {access_token}")


Recommended Free Ebook
Similar Articles