DEV Community

Cover image for Exploring SharePoint with Microsoft Graph API
≀Paulo Portela
≀Paulo Portela

Posted on • Edited on

Exploring SharePoint with Microsoft Graph API

Introduction

SharePoint, a robust collaboration platform by Microsoft, facilitates document management and team collaboration within organizations. Integrating SharePoint functionalities into applications is made seamless through Microsoft Graph API, offering a comprehensive set of endpoints for programmatic access.

Before diving into utilizing the following code, users need to register their application and configure the necessary permissions in the Azure Portal. This ensures secure and authorized access to SharePoint resources.

Index

  • Registering Application and Configuring Permissions
  • Initialization
  • Authentication
  • Retrieving Site IDs
  • Conclusion

Registering Application and Configuring Permissions

To utilize the SharePoint library effectively, users must register their application in the Azure Portal and configure the appropriate permissions to access SharePoint resources. This step is crucial for authentication and ensuring secure interactions with SharePoint.

To register your application in the Azure Portal, visit Azure Portal and follow the steps below:

  1. Navigate to the Azure Portal and sign in with your Azure account.
  2. Go to the "App registrations" page.
  3. Click on "New registration" to register a new application.
  4. Provide a name for your application and choose the appropriate supported account types.
  5. Once the registration is complete, note down the Application (client) ID, Directory (tenant) ID, and create a client secret for authentication.

After registering the application, it's essential to configure the required permissions to access SharePoint resources. Navigate to the "API permissions" page of your registered application and grant the necessary permissions for SharePoint access.

Initialization

The SharePoint library is initialized with credentials necessary for authentication. The library leverages the requests module for making HTTP requests to the Microsoft Graph API.

import base64
import dataclasses
import json
import logging
from requests.sessions import Session

@dataclasses.dataclass
class Configuration(object):
    client_id: str = None
    client_secret: str = None
    tenant_id: str = None
    token: str = None

@dataclasses.dataclass
class Response:
    status_code: int
    content: list | dict | str | None = None

class SharePoint(object):
    def __init__(self, credentials: dict) -> None:
        """
        Initializes variables and performs authentication.

        Args:
            credentials (dict): Credentials.
        """
        logging.basicConfig(level=logging.INFO)
        self.session: Session = Session()
        self.__configuration = self.auth(credentials=credentials)
Enter fullscreen mode Exit fullscreen mode

Authentication

Authentication with the Microsoft Graph API involves obtaining an access token using the provided client ID, client secret, and tenant ID. This token is then used to authorize subsequent requests to SharePoint resources.

class SharePoint(object):
    def auth(self, credentials: dict) -> Configuration:
        """
        Authentication.
        Performs authentication process to obtain the token.

        Args:
            credentials (dict): Credentials.

        Returns:
            Configuration: Access configuration.
        """
        configuration = Configuration()
        configuration.client_id = credentials["custom_metadata"]["client_id"]
        configuration.tenant_id = credentials["custom_metadata"]["tenant_id"]
        configuration.client_secret = base64.b64decode(credentials["value"]).decode("utf-8")

        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        url_auth = f"https://login.microsoftonline.com/{configuration.tenant_id}/oauth2/v2.0/token"
        body = {"grant_type": "client_credentials",
                "client_id": configuration.client_id,
                "client_secret": configuration.client_secret,
                "scope": "https://graph.microsoft.com/.default"}

        response = self.session.post(url=url_auth, data=body, headers=headers, verify=True)

        if response.status_code == 200:
            configuration.token = json.loads(response.content.decode("utf-8"))["access_token"]
            return configuration
Enter fullscreen mode Exit fullscreen mode

Retrieving Site IDs

Once authenticated, the library allows retrieving a list of Site IDs based on the provided filter. It constructs the appropriate query URL, adds necessary headers including the authorization token, and sends a GET request to the Microsoft Graph API.

class SharePoint(object):
    def get_site_id(self, filter: str, save_as: str | None = None) -> Response:
        """
        Gets a list of Site IDs based on the indicated filter.

        Args:
            filter: Filter used to list sites.
              Example: filter=Automate
            save_as: If entered, it allows saving the results in a file in Json format.

        Returns: HTTP status code and list.
        """
        headers = {"Authorization": f"Bearer {self.__configuration.token}",
                   "Content-Type": "application/json",
                   "Accept": "application/json"}

        url_query = f"https://graph.microsoft.com/v1.0/sites?search='{quote(filter)}'"

        response = self.session.get(url=url_query, headers=headers, verify=True)

        content = None
        if response.status_code == 200:
            if save_as is not None:
                with open(file=save_as, mode="wb") as file:
                    file.write(response.content)

            content_raw = response.json()["value"]
            content = [dict(data) for data in TypeAdapter(list[DataStructure]).validate_python(content_raw)]

        return Response(status_code=response.status_code, content=content)
Enter fullscreen mode Exit fullscreen mode

Other API Calls

Beyond retrieving Site IDs, the Microsoft Graph API supports various other API calls for interacting with SharePoint resources. Some of the functionalities include:

  • Creating, updating, and deleting SharePoint sites.
  • Managing lists, libraries, and items within SharePoint sites.
  • Accessing user and group information.
  • Managing permissions and access control.
  • Interacting with files and folders stored in SharePoint.

Conclusion

The code presented here offers a convenient way to interact with SharePoint resources using the Microsoft Graph API. With streamlined authentication and simplified API calls, developers can efficiently integrate SharePoint functionalities into their Python applications.

Top comments (0)