Skip to main content

Office 365 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:

  • app principals flow: AuthenticationContext.ctx_auth.acquire_token_for_app(client_id, client_secret) (refer Granting access using SharePoint App-Only for a details)
  • user credentials flow:AuthenticationContext.ctx_auth.acquire_token_for_user(username, password)
  • certificate credentials flow ClientContext.connect_with_certificate(site_url, client_id,thumbprint, certificate_path)

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))

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

ADAL Python library is utilized to authenticate users to Active Directory (AD) and obtain tokens

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
def get_token(auth_ctx):
    token = auth_ctx.acquire_token_with_client_credentials(
        "https://graph.microsoft.com",
        "{client_id}",
        "{client_secret}")
    return token


tenant_name = "{your-tenant-prefix}.onmicrosoft.com"
client = GraphClient(tenant_name, get_token)

message_json = {
    "Message": {
        "Subject": "Meet for lunch?",
        "Body": {
            "ContentType": "Text",
            "Content": "The new cafeteria is open."
        },
        "ToRecipients": [
            {
                "EmailAddress": {
                    "Address": "jdoe@contoso.onmicrosoft.com"
                }
            }
        ]
    },
    "SaveToSentItems": "false"
}

login_name = "mdoe@contoso.onmicrosoft.com"
client.users[login_name].send_mail(message_json)
client.execute_query()

Working with OneDrive API

Documentation

OneDrive Graph API reference

Authentication

ADAL Python library is utilized to authenticate users to Active Directory (AD) and obtain tokens

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
def get_token(auth_ctx):
    """Acquire token via client credential flow (ADAL Python library is utilized)"""
    token = auth_ctx.acquire_token_with_client_credentials(
        "https://graph.microsoft.com",
        "{client_id}",
        "{client_secret}")
    return token


tenant_name = "contoso.onmicrosoft.com"
client = GraphClient(tenant_name, get_token)
drives = client.drives
client.load(drives)
client.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("{tenant_name}", get_token)
# retrieve drive properties 
drive = client.users["{user_id_or_principal_name}"].drive
client.load(drive)
client.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
    client.load(drive_items)
    client.execute_query()
    for drive_item in drive_items:
        if not drive_item.file.is_server_object_null:  # is file?
            # download file content
            with open(os.path.join(local_path, drive_item.name), 'wb') as local_file:
                drive_item.download(local_file)
                client.execute_query()

Refer OneDrive examples section for a more examples.

Working with Microsoft Teams API

Authentication

ADAL Python library is utilized to authenticate users to Active Directory (AD) and obtain tokens

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, get_token)
new_team = client.groups["{group_id}"].add_team()
client.execute_query()

where

def get_token(auth_ctx):
    """Acquire token via client credential flow (ADAL Python library is utilized)
    :type auth_ctx: adal.AuthenticationContext
    """
    token = auth_ctx.acquire_token_with_client_credentials(
        "https://graph.microsoft.com",
        "{client_id}",
        "{client_secret}")
    return token

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.2.1.tar.gz (138.1 kB view details)

Uploaded Source

Built Distribution

File details

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

File metadata

  • Download URL: Office365-REST-Python-Client-2.2.1.tar.gz
  • Upload date:
  • Size: 138.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/45.2.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.8.2

File hashes

Hashes for Office365-REST-Python-Client-2.2.1.tar.gz
Algorithm Hash digest
SHA256 dfaa0f55d80a018d7728b0f30682060311aa67225571849806c69daf9dc4a0e5
MD5 7f1b77bc4e74b5138a90d7ae81f5572f
BLAKE2b-256 f0bd35d43c3b11e49867bf23d43ae199e123df1c6906969d726577a3d9631d83

See more details on using hashes here.

File details

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

File metadata

  • Download URL: Office365_REST_Python_Client-2.2.1-py3-none-any.whl
  • Upload date:
  • Size: 416.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/45.2.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.8.2

File hashes

Hashes for Office365_REST_Python_Client-2.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ccd1e5ba5fafc375cca0947e84a0c94535d1bd8660b932789833305f8e7b4bd3
MD5 f09b19d9871ec734748fa36d69d265c5
BLAKE2b-256 d9470a8189ef781a1f39541042ef23ab03191b29aa4e6651f0ebd0e487fef940

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