Microsoft 365 & Microsoft Graph Library for Python
npx @tessl/cli install tessl/pypi-office365-rest-python-client@2.6.00
# Office365-REST-Python-Client
1
2
A comprehensive Python library for interacting with Microsoft 365 and Microsoft Graph APIs, enabling developers to build applications that integrate with SharePoint, Outlook, OneDrive, Teams, OneNote, and Planner services. It offers a unified client interface for both legacy SharePoint REST APIs and modern Microsoft Graph endpoints, with support for various authentication methods including Azure AD, NTLM, and certificate-based authentication.
3
4
## Package Information
5
6
- **Package Name**: Office365-REST-Python-Client
7
- **Language**: Python
8
- **Installation**: `pip install Office365-REST-Python-Client`
9
10
## Core Imports
11
12
```python
13
from office365.graph_client import GraphClient
14
from office365.sharepoint.client_context import ClientContext
15
from office365.azure_env import AzureEnvironment
16
```
17
18
For authentication:
19
20
```python
21
from office365.runtime.auth.user_credential import UserCredential
22
from office365.runtime.auth.client_credential import ClientCredential
23
from office365.runtime.auth.authentication_context import AuthenticationContext
24
```
25
26
For specific services:
27
28
```python
29
from office365.directory.users.user import User
30
from office365.sharepoint.files.file import File
31
from office365.sharepoint.webs.context_web_information import ContextWebInformation
32
from office365.sharepoint.request_user_context import RequestUserContext
33
from office365.onedrive.drives.drive import Drive
34
from office365.teams.team import Team
35
```
36
37
## Basic Usage
38
39
### Microsoft Graph API Access
40
41
```python
42
from office365.graph_client import GraphClient
43
44
# Authenticate with client credentials
45
client = GraphClient(tenant="your-tenant-id").with_client_secret(
46
client_id="your-client-id",
47
client_secret="your-client-secret"
48
)
49
50
# Get current user information
51
me = client.me.get().execute_query()
52
print(f"Hello {me.display_name}")
53
54
# List all users
55
users = client.users.get().top(10).execute_query()
56
for user in users:
57
print(user.display_name, user.mail)
58
59
# Access OneDrive files
60
drive = client.me.drive.get().execute_query()
61
items = drive.root.children.get().execute_query()
62
for item in items:
63
print(item.name, item.web_url)
64
```
65
66
### SharePoint REST API Access
67
68
```python
69
from office365.sharepoint.client_context import ClientContext
70
71
# Authenticate to SharePoint site
72
ctx = ClientContext("https://tenant.sharepoint.com/sites/sitename").with_client_credentials(
73
client_id="your-client-id",
74
client_secret="your-client-secret"
75
)
76
77
# Get site information
78
web = ctx.web.get().execute_query()
79
print(f"Site title: {web.title}")
80
81
# Work with document libraries
82
docs_lib = ctx.web.lists.get_by_title("Documents")
83
items = docs_lib.items.get().execute_query()
84
for item in items:
85
print(item.properties["Title"])
86
87
# Upload a file
88
with open("local-file.txt", "rb") as file_content:
89
target_file = docs_lib.root_folder.upload_file("remote-file.txt", file_content)
90
ctx.execute_query()
91
print(f"File uploaded: {target_file.serverRelativeUrl}")
92
```
93
94
## Architecture
95
96
The library follows a dual-client architecture to support both modern and legacy Microsoft APIs:
97
98
- **GraphClient**: Primary interface for Microsoft Graph API (modern, unified API)
99
- **ClientContext**: Primary interface for SharePoint REST API (legacy, SharePoint-specific)
100
- **Authentication Layer**: Unified authentication supporting multiple flows (OAuth2, certificates, interactive)
101
- **Entity Framework**: Base classes for all API resources with consistent query patterns
102
- **Runtime Layer**: HTTP handling, request batching, error management, and OData protocol support
103
104
Both clients provide fluent interfaces with method chaining, batch operations, and comprehensive error handling. The entity framework ensures consistent patterns across all API surfaces while the runtime layer handles authentication, retry logic, and protocol-specific requirements.
105
106
## Capabilities
107
108
### Authentication and Client Setup
109
110
Comprehensive authentication support for enterprise environments including client credentials, certificate-based authentication, interactive flows, and legacy authentication methods for SharePoint.
111
112
```python { .api }
113
class GraphClient:
114
def __init__(self, tenant: str = None, scopes: List[str] = None, token_cache=None, environment=None): ...
115
116
def with_client_secret(self, client_id: str, client_secret: str) -> 'GraphClient': ...
117
def with_certificate(self, client_id: str, thumbprint: str, private_key: str) -> 'GraphClient': ...
118
def with_token_interactive(self, client_id: str, username: str = None) -> 'GraphClient': ...
119
def with_username_and_password(self, client_id: str, username: str, password: str) -> 'GraphClient': ...
120
def with_device_flow(self, tenant: str, client_id: str, scopes: List[str] = None) -> 'GraphClient': ...
121
def with_access_token(self, token_func: Callable[[], dict]) -> 'GraphClient': ...
122
123
class ClientContext:
124
def with_client_credentials(self, client_id: str, client_secret: str) -> 'ClientContext': ...
125
def with_client_certificate(self, tenant: str, client_id: str, thumbprint: str, cert_path: str = None, private_key: str = None, scopes: List[str] = None, passphrase: str = None) -> 'ClientContext': ...
126
def with_interactive(self, tenant: str, client_id: str, scopes: List[str] = None) -> 'ClientContext': ...
127
def with_user_credentials(self, username: str, password: str) -> 'ClientContext': ...
128
def with_device_flow(self, tenant: str, client_id: str, scopes: List[str] = None) -> 'ClientContext': ...
129
def with_access_token(self, token_func: Callable[[], dict]) -> 'ClientContext': ...
130
def with_credentials(self, credentials: Union[UserCredential, ClientCredential]) -> 'ClientContext': ...
131
```
132
133
[Authentication & Setup](./authentication.md)
134
135
### Microsoft Graph Directory Services
136
137
Complete Azure Active Directory management including users, groups, applications, devices, and organizational relationships through the Microsoft Graph API.
138
139
```python { .api }
140
class GraphClient:
141
@property
142
def users(self) -> UserCollection: ...
143
@property
144
def groups(self) -> GroupCollection: ...
145
@property
146
def applications(self) -> ApplicationCollection: ...
147
@property
148
def devices(self) -> DeviceCollection: ...
149
@property
150
def me(self) -> User: ...
151
152
class User:
153
display_name: str
154
mail: str
155
user_principal_name: str
156
def get(self) -> 'User': ...
157
def update(self) -> 'User': ...
158
def delete_object(self) -> 'User': ...
159
```
160
161
[Directory Services](./directory-services.md)
162
163
### OneDrive and File Management
164
165
OneDrive storage access with comprehensive file operations including upload, download, sharing, and metadata management through Microsoft Graph API.
166
167
```python { .api }
168
class GraphClient:
169
@property
170
def drives(self) -> DriveCollection: ...
171
@property
172
def sites(self) -> SiteCollection: ...
173
174
class Drive:
175
@property
176
def root(self) -> DriveItem: ...
177
def get_by_path(self, path: str) -> DriveItem: ...
178
179
class DriveItem:
180
name: str
181
web_url: str
182
@property
183
def children(self) -> DriveItemCollection: ...
184
def upload(self, name: str, content: bytes) -> 'DriveItem': ...
185
def download(self) -> bytes: ...
186
```
187
188
[OneDrive & Files](./onedrive-files.md)
189
190
### Microsoft Teams Integration
191
192
Complete Microsoft Teams functionality including teams, channels, chats, messages, and collaborative features through Microsoft Graph API.
193
194
```python { .api }
195
class GraphClient:
196
@property
197
def teams(self) -> TeamCollection: ...
198
@property
199
def chats(self) -> ChatCollection: ...
200
201
class Team:
202
display_name: str
203
description: str
204
@property
205
def channels(self) -> ChannelCollection: ...
206
@property
207
def members(self) -> ConversationMemberCollection: ...
208
209
class Chat:
210
topic: str
211
chat_type: str
212
@property
213
def messages(self) -> ChatMessageCollection: ...
214
```
215
216
[Teams Integration](./teams.md)
217
218
### SharePoint Sites and Content
219
220
Comprehensive SharePoint functionality including sites, lists, libraries, files, folders, and content management through SharePoint REST API.
221
222
```python { .api }
223
class ClientContext:
224
@property
225
def web(self) -> Web: ...
226
@property
227
def site(self) -> Site: ...
228
@property
229
def context_info(self) -> ContextWebInformation: ...
230
@property
231
def authentication_context(self) -> AuthenticationContext: ...
232
@property
233
def base_url(self) -> str: ...
234
@property
235
def me(self) -> RequestUserContext: ...
236
@property
237
def lists(self) -> ListCollection: ...
238
239
class Web:
240
title: str
241
url: str
242
@property
243
def lists(self) -> ListCollection: ...
244
@property
245
def folders(self) -> FolderCollection: ...
246
247
class List:
248
title: str
249
@property
250
def items(self) -> ListItemCollection: ...
251
@property
252
def root_folder(self) -> Folder: ...
253
```
254
255
[SharePoint Sites](./sharepoint-sites.md)
256
257
### Email and Calendar Services
258
259
Outlook integration for email, calendar, contacts, and mailbox management through Microsoft Graph API with comprehensive messaging capabilities.
260
261
```python { .api }
262
class GraphClient:
263
@property
264
def me(self) -> User: ...
265
266
class User:
267
@property
268
def messages(self) -> MessageCollection: ...
269
@property
270
def mail_folders(self) -> MailFolderCollection: ...
271
@property
272
def events(self) -> EventCollection: ...
273
@property
274
def calendar(self) -> Calendar: ...
275
276
class Message:
277
subject: str
278
body: ItemBody
279
from_: Recipient
280
to_recipients: List[Recipient]
281
def send(self) -> None: ...
282
```
283
284
[Email & Calendar](./email-calendar.md)
285
286
## Types
287
288
```python { .api }
289
class Entity:
290
"""Base class for all API entities with common operations."""
291
def get(self) -> 'Entity': ...
292
def update(self) -> 'Entity': ...
293
def delete(self) -> None: ...
294
def execute_query(self) -> 'Entity': ...
295
296
class EntityCollection:
297
"""Base class for collections with query and pagination support."""
298
def get(self) -> 'EntityCollection': ...
299
def filter(self, expression: str) -> 'EntityCollection': ...
300
def select(self, properties: List[str]) -> 'EntityCollection': ...
301
def top(self, count: int) -> 'EntityCollection': ...
302
def skip(self, count: int) -> 'EntityCollection': ...
303
def order_by(self, property_name: str, ascending: bool = True) -> 'EntityCollection': ...
304
305
class ClientResult:
306
"""Container for API response data."""
307
value: Any
308
309
class RequestOptions:
310
"""Configuration options for HTTP requests."""
311
headers: Dict[str, str]
312
timeout: int
313
314
class AzureEnvironment:
315
"""Azure cloud environment configuration."""
316
Global: 'AzureEnvironment'
317
China: 'AzureEnvironment'
318
USGovernment: 'AzureEnvironment'
319
Germany: 'AzureEnvironment'
320
321
class ContextWebInformation:
322
"""SharePoint site context information."""
323
form_digest_value: str
324
lib_resource: str
325
supported_schema_versions: List[str]
326
327
class AuthenticationContext:
328
"""Authentication context for SharePoint requests."""
329
url: str
330
environment: str
331
332
class RequestUserContext:
333
"""Current user context for SharePoint."""
334
login_name: str
335
title: str
336
email: str
337
338
class UserCredential:
339
"""User credential for authentication."""
340
def __init__(self, username: str, password: str): ...
341
342
class ClientCredential:
343
"""Client credential for authentication."""
344
def __init__(self, client_id: str, client_secret: str): ...
345
```