Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Microsoft 365 & Microsoft Graph Library for Python

License

NotificationsYou must be signed in to change notification settings

vgrem/office365-rest-python-client

Microsoft 365 & Microsoft Graph library for Python

Usage

  1. Installation
  2. Working with SharePoint API
  3. Working with Outlook API
  4. Working with OneDrive and SharePoint API v2 APIs
  5. Working with Teams API
  6. Working with OneNote API
  7. Working with Planner API

Status

DownloadsPyPIPyPI pyversionsBuild Status

Installation

Use pip:

pip install office365-rest-python-client

Note

Alternatively thelatest version could be directly installed via GitHub:

pip install git+https://github.com/vgrem/office365-rest-python-client.git

Authentication

For the following examples, relevant credentials can be found in the Azure Portal.

Steps to access:

  1. Login to the home page of the Azure Portal
  2. Navigate to "Azure Active Directory" using the three bars in the top right corner of the portal
  3. Select "App registrations" in the navigation panel on the left
  4. Search for and select your relevant application
  5. In the application's "Overview" page, the client id can be found under "Application (client) id"
  6. In the application's "Certificates & Secrets" page, the client secret can be found under the "Value" of the "Client Secrets." If there is no client secret yet, create one here.

Working with SharePoint API

TheClientContext client provides the support for a legacy SharePoint REST and OneDrive for Business REST APIs,the list of supported versions:

Authentication

The following auth flows are supported:

1. Using a SharePoint App-Only principal (client credentials flow)

This auth method is compatible with SharePoint on-premises and still relevantmodel in both SharePoint on-premises as SharePoint Online,the following methods are available:

  • ClientContext.with_credentials(client_credentials)
  • ClientContext.with_client_credentials(client_id, client_secret)

Usage:

client_credentials = ClientCredential('{client_id}','{client_secret}')ctx = ClientContext('{url}').with_credentials(client_credentials)

Documentation:

Example:connect_with_app_principal.py

2. Using username and password

Usage:

user_credentials = UserCredential('{username}','{password}')ctx = ClientContext('{url}').with_credentials(user_credentials)

Example:connect_with_user_credential.py

3. Using an Azure AD application (certificate credentials flow)

Documentation:

Example:with_certificate.py

4. Interactive

to login interactively i.e. via a local browser

Prerequisite:

In Azure Portal, configure the Redirect URI of your"Mobile and Desktop application" ashttp://localhost.

Example:connect_interactive.py

Usage:

fromoffice365.sharepoint.client_contextimportClientContextctx=ClientContext("{site-url}").with_interactive("{tenant-name-or-id}","{client-id}")me=ctx.web.current_user.get().execute_query()print(me.login_name)

5. Browser session cookies (SharePoint Online)

Authenticate using cookies from a real browser session (e.g., Playwright). No Azure AD app registration required.

Usage:

fromoffice365.sharepoint.client_contextimportClientContextdefcookie_source():# Return a dict with FedAuth/rtFa/SPOIDCRL values or an AuthCookies instancereturn {"FedAuth":"...","rtFa":"...","SPOIDCRL":"..."}ctx=ClientContext("https://contoso.sharepoint.com/sites/demo").with_cookies(cookie_source,ttl_seconds=None)web=ctx.web.get().execute_query()print(web.title)

Example:auth_cookies.py

Notes:

  • ttl_seconds is optional. Use it to periodically refresh cookies from your source if it’s cheap (e.g., file read).
  • Cookies are secrets. Do not log them; secure any storage (e.g., Playwrightstorage_state.json).

Examples

There aretwo approaches available to perform API queries:

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

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

fromoffice365.runtime.auth.user_credentialimportUserCredentialfromoffice365.sharepoint.client_contextimportClientContextsite_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. SharePointRequest class - where you construct REST queries (and no model is involved)

    The example demonstrates how to readWeb properties:

importjsonfromoffice365.runtime.auth.user_credentialimportUserCredentialfromoffice365.sharepoint.requestimportSharePointRequestsite_url="https://{your-tenant-prefix}.sharepoint.com"request=SharePointRequest(site_url).with_credentials(UserCredential("{username}","{password}"))response=request.execute_request("web")json=json.loads(response.content)web_title=json['d']['Title']print("Web title: {0}".format(web_title))

Tip: You can also authenticateSharePointRequest with cookies usingwith_cookies(cookie_source, ttl_seconds=None).

For SharePoint-specific examples, see:
📌SharePoint examples guide

Support for Azure environments

To enable authentication to specific Azure environment endpoints, add theenvironment parameter when calling theClientContext class with.with_user_credentials,.with_client_credentials, or.with_credentials

Example:

fromoffice365.azure_envimportAzureEnvironmentfromoffice365.sharepoint.client_contextimportClientContextfromoffice365.runtime.auth.client_credentialimportClientCredentialclient_credentials=ClientCredential('{client_id}','{client_secret}')ctx=ClientContext('{site-url}',environment=AzureEnvironment.USGovernmentHigh).with_credentials(client_credentials)

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 APIv2.0 version (preferable nowadays, refertransition to Microsoft Graph-based Outlook REST API for a details)
    -OutlookClient which targets Outlook APIv1.0 version (not recommended for usage sincev1.0 version is being deprecated.)

Authentication

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

UsingMicrosoft Authentication Library (MSAL) for Python

Note: access token is getting acquired viaClient Credential flowin the provided examples. Other forms of token acquisition can be found here:https://msal-python.readthedocs.io/en/latest/

fromoffice365.graph_clientimportGraphClientclient=GraphClient(tenant='{tenant_name_or_id}').with_client_secret(client_id='{client_id}',client_secret='{client_secret}')

Example:with_client_secret

But in terms of Microsoft Graph API authentication, another OAuth spec compliant librariessuch asadalare supported as well.

UsingADAL Python

Usage

importadalfromoffice365.graph_clientimportGraphClientdefacquire_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}")returntokenclient=GraphClient(acquire_token_func)

Example

The example demonstrates how to send an email viaMicrosoft Graph endpoint.

Note: access token is getting acquired viaClient Credential flow

fromoffice365.graph_clientimportGraphClientclient=GraphClient(tenant='{tenant_name_or_id}').with_username_and_password('{client_id}','{username}','{password}')client.me.send_mail(subject="Meet for lunch?",body="The new cafeteria is open.",to_recipients=["fannyd@contoso.onmicrosoft.com"]).execute_query()

Additional examples & scenarios:

Refer toexamples section for other scenarios

Working with OneDrive and SharePoint v2 APIs

Documentation

OneDrive Graph API reference

Authentication

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

importmsaldefacquire_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"])returntoken

Examples

Example: list available drives

The example demonstrates how to enumerate and print drive's urlwhich corresponds tolist available drives endpoint

Note: access token is getting acquired viaClient Credential flow

fromoffice365.graph_clientimportGraphClienttenant_name="contoso.onmicrosoft.com"client=GraphClient(tenant=tenant_name)drives=client.drives.get().execute_query()fordriveindrives:print("Drive url: {0}".format(drive.web_url))
Example: download the contents of a DriveItem(folder facet)
fromoffice365.graph_clientimportGraphClientclient=GraphClient(tenant="contoso.onmicrosoft.com")# retrieve drive propertiesdrive=client.users["{user_id_or_principal_name}"].drive.get().execute_query()# download files from OneDrive into local folderwithtempfile.TemporaryDirectory()aspath:download_files(drive.root,path)

where

defdownload_files(remote_folder,local_path):drive_items=remote_folder.children.get().execute_query()fordrive_itemindrive_items:ifdrive_item.fileisnotNone:# is file?# download file contentwithopen(os.path.join(local_path,drive_item.name),'wb')aslocal_file:drive_item.download(local_file).execute_query()

Additional examples:

Refer toOneDrive examples section for more examples.

Working with Microsoft Teams API

Authentication

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

Examples

Example: create a new team under a group

The example demonstrates how create a new team under a groupwhich corresponds toCreate team endpoint

fromoffice365.graph_clientimportGraphClientclient=GraphClient(acquire_token_func)new_team=client.groups["{group-id}"].add_team().execute_query_retry()

Additional examples:

Refer toexamples section for other scenarios

Working with Microsoft Onenote API

The library supports OneNote API in terms of calls to a user's OneNote notebooks, sections, and pages in a personal or organization account

Example: Create a new page

fromoffice365.graph_clientimportGraphClientclient=GraphClient(tenant='{tenant_name_or_id}').with_username_and_password('{client_id}','{username}','{password}')files= {}withopen("./MyPage.html",'rb')asf, \open("./MyImage.png",'rb')asimg_f, \open("./MyDoc.pdf",'rb')aspdf_f:files["imageBlock1"]=img_ffiles["fileBlock1"]=pdf_fpage=client.me.onenote.pages.add(presentation_file=f,attachment_files=files).execute_query()

Working with Microsoft Planner API

The example demonstrates how to create a new planner taskwhich corresponds toCreate plannerTask endpoint:

fromoffice365.graph_clientimportGraphClientclient=GraphClient(acquire_token_func)task=client.planner.tasks.add(title="New task",planId="--plan id goes here--").execute_query()

Third Party Libraries and Dependencies

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

ThanksTo

Powerful Python IDEPycharm fromJetbrains.


[8]ページ先頭

©2009-2025 Movatter.jp