Skip to main content

Microsoft 365 & Microsoft Graph Library for Python

Project description

About

Office 365 & Microsoft Graph library for Python

Usage

  1. Installation
  2. Working with SharePoint API
  3. Working with Outlook API
  4. Working with OneDrive API
  5. Working with Microsoft Teams API

Status

Downloads PyPI PyPI pyversions Build Status

Installation

Use pip:

pip install Office365-REST-Python-Client

Note

Alternatively the latest version could be directly installed via GitHub:

pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git

Working with SharePoint API

The list of supported API versions:

Authentication

The following auth flows are supported:

Examples

There are two approaches available to perform API queries:

  1. ClientContext class - where you target SharePoint resources such as Web, ListItem and etc (recommended)
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
site_url = "https://{your-tenant-prefix}.sharepoint.com"
ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web title: {0}".format(web.properties['Title']))

or alternatively via method chaining (a.k.a Fluent Interface):

from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
site_url = "https://{your-tenant-prefix}.sharepoint.com"
ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
web = ctx.web.get().execute_query()
print("Web title: {0}".format(web.properties['Title']))
  1. RequestOptions class - where you construct REST queries (and no model is involved)

    The example demonstrates how to read Web properties:

import json
from office365.runtime.auth.user_credential import UserCredential
from office365.runtime.http.request_options import RequestOptions
from office365.sharepoint.client_context import ClientContext
site_url = "https://{your-tenant-prefix}.sharepoint.com"
ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
request = RequestOptions("{0}/_api/web/".format(site_url))
response = ctx.execute_request_direct(request)
json = json.loads(response.content)
web_title = json['d']['Title']
print("Web title: {0}".format(web_title))

The list of examples:

Working with Outlook API

The list of supported APIs:

Since Outlook REST APIs are available in both Microsoft Graph and the Outlook API endpoint, the following clients are available:

  • GraphClient which targets Outlook API v2.0 version (preferable nowadays, refer transition to Microsoft Graph-based Outlook REST API for a details)
    - OutlookClient which targets Outlook API v1.0 version (not recommended for usage since v1.0 version is being deprecated.)

Authentication

The Microsoft Authentication Library (MSAL) for Python which comes as a dependency is used as a default library to obtain tokens to call Microsoft Graph API.

Using Microsoft Authentication Library (MSAL) for Python

Note: access token is getting acquired via Client Credential flow in the provided examples

import msal
from office365.graph_client import GraphClient

def acquire_token():
    """
    Acquire token via MSAL
    """
    authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
    app = msal.ConfidentialClientApplication(
        authority=authority_url,
        client_id='{client_id}',
        client_credential='{client_secret}'
    )
    token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    return token


client = GraphClient(acquire_token)

But in terms of Microsoft Graph API authentication, another Microsoft Authentication Client compliant libraries such as adal are supported as well.

Using ADAL Python

Usage

import adal
from office365.graph_client import GraphClient

def acquire_token_func():
    authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
    auth_ctx = adal.AuthenticationContext(authority_url)
    token = auth_ctx.acquire_token_with_client_credentials(
        "https://graph.microsoft.com",
        "{client_id}",
        "{client_secret}")
    return token

client = GraphClient(acquire_token_func)

Example

The example demonstrates how to send an email via Microsoft Graph endpoint.

Note: access token is getting acquired via Client Credential flow

from office365.graph_client import GraphClient

client = GraphClient(acquire_token_func)

message = client.me.messages.new()  # type: Message
message.subject = "Meet for lunch?"
message.body = "The new cafeteria is open."
message.to_recipients = ["fannyd@contoso.onmicrosoft.com"]

client.me.send_mail(message).execute_query()

Working with OneDrive API

Documentation

OneDrive Graph API reference

Authentication

The Microsoft Authentication Library (MSAL) for Python which comes as a dependency is used to obtain token

import msal

def acquire_token_func():
    """
    Acquire token via MSAL
    """
    authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
    app = msal.ConfidentialClientApplication(
        authority=authority_url,
        client_id='{client_id}',
        client_credential='{client_secret}'
    )
    token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    return token

Examples

Example: list available drives

The example demonstrates how to enumerate and print drive's url which corresponds to list available drives endpoint

Note: access token is getting acquired via Client Credential flow

from office365.graph_client import GraphClient

tenant_name = "contoso.onmicrosoft.com"
client = GraphClient(acquire_token_func)
drives = client.drives.get().execute_query()
for drive in drives:
    print("Drive url: {0}".format(drive.web_url))
Example: download the contents of a DriveItem(folder facet)
from office365.graph_client import GraphClient
client = GraphClient(acquire_token_func)
# retrieve drive properties 
drive = client.users["{user_id_or_principal_name}"].drive.get().execute_query()
# download files from OneDrive into local folder 
with tempfile.TemporaryDirectory() as path:
    download_files(drive.root, path)

where

def download_files(remote_folder, local_path):
    drive_items = remote_folder.children.get().execute_query()
    for drive_item in drive_items:
        if drive_item.file is not None:  # is file?
            # download file content
            with open(os.path.join(local_path, drive_item.name), 'wb') as local_file:
                drive_item.download(local_file).execute_query()

Refer OneDrive examples section for a more examples.

Working with Microsoft Teams API

Authentication

The Microsoft Authentication Library (MSAL) for Python which comes as a dependency is used to obtain token

Examples

Example: create a new team under a group

The example demonstrates how create a new team under a group which corresponds to Create team endpoint

from office365.graph_client import GraphClient
tenant_name = "contoso.onmicrosoft.com"
client = GraphClient(tenant_name, acquire_token_func)
new_team = client.groups["{group_id}"].add_team().execute_query_retry()

Third Party Libraries and Dependencies

The following libraries will be installed when you install the client library:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Office365-REST-Python-Client-2.3.8.tar.gz (211.8 kB view details)

Uploaded Source

Built Distribution

File details

Details for the file Office365-REST-Python-Client-2.3.8.tar.gz.

File metadata

  • Download URL: Office365-REST-Python-Client-2.3.8.tar.gz
  • Upload date:
  • Size: 211.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.7.1 pkginfo/1.7.1 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.5

File hashes

Hashes for Office365-REST-Python-Client-2.3.8.tar.gz
Algorithm Hash digest
SHA256 8e6fac1bca82cca0fde63dd43d2bccde16c53d0f257585067c261f6eb2b0de73
MD5 1a01e02e1f998af099278b91932c815a
BLAKE2b-256 db5bcfa51b3f9eb659df37e70e6f2ac19bc623fc9eb748e4f320fae2f5a14c53

See more details on using hashes here.

File details

Details for the file Office365_REST_Python_Client-2.3.8-py3-none-any.whl.

File metadata

  • Download URL: Office365_REST_Python_Client-2.3.8-py3-none-any.whl
  • Upload date:
  • Size: 430.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.7.1 pkginfo/1.7.1 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.5

File hashes

Hashes for Office365_REST_Python_Client-2.3.8-py3-none-any.whl
Algorithm Hash digest
SHA256 9a72c766b49e2225e2bc27e9bae2ba6259f5e6daf15e0a05463645b529f3eeda
MD5 80e7c93b3a3f4a0ae59014c37978bb28
BLAKE2b-256 5598d7f0f12013fb22cb981999c06d24ecac8d298a085f55762a41b4c43f5004

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page