0
# Main API Client
1
2
The Canvas class serves as the primary entry point for all Canvas API operations. It handles authentication, provides access to all Canvas resources, and manages global operations like searching and GraphQL queries.
3
4
## Capabilities
5
6
### Initialization
7
8
Initialize the Canvas API client with your Canvas instance URL and access token.
9
10
```python { .api }
11
class Canvas:
12
def __init__(self, base_url: str, access_token: str):
13
"""
14
Initialize Canvas API client.
15
16
Parameters:
17
- base_url: The base URL of the Canvas instance's API (without /api/v1)
18
- access_token: The API key to authenticate requests with
19
"""
20
```
21
22
### Current User Operations
23
24
Get information about the currently authenticated user.
25
26
```python { .api }
27
def get_current_user(self) -> CurrentUser:
28
"""Return details of the current user."""
29
```
30
31
### Course Operations
32
33
Access and manage courses across the Canvas instance.
34
35
```python { .api }
36
def get_course(self, course, use_sis_id: bool = False, **kwargs) -> Course:
37
"""
38
Retrieve a course by its ID.
39
40
Parameters:
41
- course: The object or ID of the course to retrieve
42
- use_sis_id: Whether course_id is an SIS ID (default: False)
43
44
Returns:
45
Course object
46
"""
47
48
def get_courses(self, **kwargs) -> PaginatedList[Course]:
49
"""
50
Return a list of active courses for the current user.
51
52
Returns:
53
Paginated list of Course objects
54
"""
55
56
def get_course_nickname(self, course, **kwargs) -> CourseNickname:
57
"""Return the nickname for the given course."""
58
59
def get_course_nicknames(self, **kwargs) -> PaginatedList[CourseNickname]:
60
"""Return all course nicknames set by the current account."""
61
62
def set_course_nickname(self, course, nickname: str, **kwargs) -> CourseNickname:
63
"""
64
Set a nickname for the given course.
65
66
Parameters:
67
- course: The Course object or ID
68
- nickname: The nickname for the course
69
"""
70
71
def clear_course_nicknames(self, **kwargs) -> bool:
72
"""Remove all stored course nicknames."""
73
```
74
75
### User Operations
76
77
Access user information and profiles.
78
79
```python { .api }
80
def get_user(self, user, id_type: str = None, **kwargs) -> User:
81
"""
82
Retrieve a user by their ID.
83
84
Parameters:
85
- user: The user's object or ID
86
- id_type: The ID type (sis_user_id, login_id, etc.)
87
88
Returns:
89
User object
90
"""
91
```
92
93
### Account Operations
94
95
Manage Canvas accounts and institutional data.
96
97
```python { .api }
98
def get_account(self, account, use_sis_id: bool = False, **kwargs) -> Account:
99
"""
100
Retrieve information on an individual account.
101
102
Parameters:
103
- account: The object or ID of the account to retrieve
104
- use_sis_id: Whether account_id is an SIS ID (default: False)
105
106
Returns:
107
Account object
108
"""
109
110
def get_accounts(self, **kwargs) -> PaginatedList[Account]:
111
"""
112
List accounts that the current user can view or manage.
113
114
Returns:
115
Paginated list of Account objects
116
"""
117
118
def get_course_accounts(self, **kwargs) -> PaginatedList[Account]:
119
"""
120
List accounts through admin course enrollments.
121
122
Returns:
123
Paginated list of Account objects
124
"""
125
126
def create_account(self, **kwargs) -> Account:
127
"""Create a new root account."""
128
129
def search_accounts(self, **kwargs) -> dict:
130
"""Return up to 5 matching account domains."""
131
```
132
133
### Communication Operations
134
135
Manage conversations and messaging across Canvas.
136
137
```python { .api }
138
def get_conversation(self, conversation, **kwargs) -> Conversation:
139
"""Return single conversation."""
140
141
def get_conversations(self, **kwargs) -> PaginatedList[Conversation]:
142
"""Return list of conversations for the current user."""
143
144
def create_conversation(self, recipients: list, body: str, **kwargs) -> list[Conversation]:
145
"""
146
Create a new conversation.
147
148
Parameters:
149
- recipients: Array of recipient IDs (can include course_ or group_ prefixes)
150
- body: The body of the message being added
151
152
Returns:
153
List of Conversation objects
154
"""
155
156
def conversations_batch_update(self, conversation_ids: list, event: str, **kwargs) -> Progress:
157
"""
158
Batch update conversations.
159
160
Parameters:
161
- conversation_ids: List of conversations to update (max 500)
162
- event: Action to take ('mark_as_read', 'mark_as_unread', 'star', 'unstar', 'archive', 'destroy')
163
164
Returns:
165
Progress object tracking the operation
166
"""
167
168
def conversations_mark_all_as_read(self, **kwargs) -> bool:
169
"""Mark all conversations as read."""
170
171
def conversations_unread_count(self, **kwargs) -> dict:
172
"""Get the number of unread conversations for the current user."""
173
174
def conversations_get_running_batches(self, **kwargs) -> dict:
175
"""Returns currently running conversation batches."""
176
```
177
178
### Group Operations
179
180
Manage groups and group categories.
181
182
```python { .api }
183
def get_group(self, group, use_sis_id: bool = False, **kwargs) -> Group:
184
"""Return data for a single group."""
185
186
def get_group_category(self, category, **kwargs) -> GroupCategory:
187
"""Get a single group category."""
188
189
def create_group(self, **kwargs) -> Group:
190
"""Create a group."""
191
```
192
193
### Calendar and Appointment Operations
194
195
Manage calendar events and appointment scheduling.
196
197
```python { .api }
198
def get_calendar_event(self, calendar_event, **kwargs) -> CalendarEvent:
199
"""Return single calendar event by ID."""
200
201
def get_calendar_events(self, **kwargs) -> PaginatedList[CalendarEvent]:
202
"""List calendar events."""
203
204
def create_calendar_event(self, calendar_event: dict, **kwargs) -> CalendarEvent:
205
"""
206
Create a new calendar event.
207
208
Parameters:
209
- calendar_event: Dictionary with event attributes including 'context_code'
210
211
Returns:
212
CalendarEvent object
213
"""
214
215
def get_appointment_group(self, appointment_group, **kwargs) -> AppointmentGroup:
216
"""Return single appointment group."""
217
218
def get_appointment_groups(self, **kwargs) -> PaginatedList[AppointmentGroup]:
219
"""List appointment groups."""
220
221
def create_appointment_group(self, appointment_group: dict, **kwargs) -> AppointmentGroup:
222
"""
223
Create new appointment group.
224
225
Parameters:
226
- appointment_group: Dictionary with 'context_codes' and 'title' keys
227
228
Returns:
229
AppointmentGroup object
230
"""
231
232
def reserve_time_slot(self, calendar_event, participant_id: str = None, **kwargs) -> CalendarEvent:
233
"""Reserve a time slot in a calendar event."""
234
```
235
236
### File and Content Operations
237
238
Access files and folders across Canvas.
239
240
```python { .api }
241
def get_file(self, file, **kwargs) -> File:
242
"""Return the standard attachment json object for a file."""
243
244
def get_folder(self, folder, **kwargs) -> Folder:
245
"""Return the details for a folder."""
246
```
247
248
### Announcement Operations
249
250
Access announcements across multiple contexts.
251
252
```python { .api }
253
def get_announcements(self, context_codes: list, **kwargs) -> PaginatedList[DiscussionTopic]:
254
"""
255
List announcements.
256
257
Parameters:
258
- context_codes: Course IDs or Course objects to request announcements from
259
260
Returns:
261
Paginated list of DiscussionTopic objects
262
"""
263
```
264
265
### Search Operations
266
267
Search for courses, users, and other Canvas resources.
268
269
```python { .api }
270
def search_all_courses(self, **kwargs) -> list:
271
"""List all courses visible in the public index."""
272
273
def search_recipients(self, **kwargs) -> list:
274
"""Find valid recipients that the current user can send messages to."""
275
```
276
277
### Section Operations
278
279
Access course sections.
280
281
```python { .api }
282
def get_section(self, section, use_sis_id: bool = False, **kwargs) -> Section:
283
"""
284
Get details about a specific section.
285
286
Parameters:
287
- section: The Section object or ID
288
- use_sis_id: Whether section_id is an SIS ID (default: False)
289
290
Returns:
291
Section object
292
"""
293
```
294
295
### Outcome Operations
296
297
Access learning outcomes and outcome groups.
298
299
```python { .api }
300
def get_outcome(self, outcome, **kwargs) -> Outcome:
301
"""
302
Return details of outcome with given ID.
303
304
Parameters:
305
- outcome: Outcome object or ID
306
307
Returns:
308
Outcome object
309
"""
310
311
def get_outcome_group(self, group, **kwargs) -> OutcomeGroup:
312
"""
313
Return details of outcome group with given ID.
314
315
Parameters:
316
- group: OutcomeGroup object or ID
317
318
Returns:
319
OutcomeGroup object
320
"""
321
322
def get_root_outcome_group(self, **kwargs) -> OutcomeGroup:
323
"""
324
Redirect to root outcome group for context.
325
326
Returns:
327
OutcomeGroup object
328
"""
329
```
330
331
### Planner Operations
332
333
Create and manage planner notes and overrides.
334
335
```python { .api }
336
def create_planner_note(self, **kwargs) -> PlannerNote:
337
"""Create a planner note for the current user."""
338
339
def create_planner_override(self, plannable_type: str, plannable_id: int, **kwargs) -> PlannerOverride:
340
"""
341
Create a planner override for the current user.
342
343
Parameters:
344
- plannable_type: Type of object being overridden
345
- plannable_id: ID of the object being overridden
346
347
Returns:
348
PlannerOverride object
349
"""
350
351
def get_planner_note(self, planner_note, **kwargs) -> PlannerNote:
352
"""
353
Retrieve a planner note for the current user.
354
355
Parameters:
356
- planner_note: PlannerNote object or ID
357
358
Returns:
359
PlannerNote object
360
"""
361
362
def get_planner_notes(self, **kwargs) -> PaginatedList[PlannerNote]:
363
"""
364
Retrieve paginated list of planner notes.
365
366
Returns:
367
Paginated list of PlannerNote objects
368
"""
369
370
def get_planner_override(self, planner_override, **kwargs) -> PlannerOverride:
371
"""
372
Retrieve a planner override for the current user.
373
374
Parameters:
375
- planner_override: PlannerOverride object or ID
376
377
Returns:
378
PlannerOverride object
379
"""
380
381
def get_planner_overrides(self, **kwargs) -> PaginatedList[PlannerOverride]:
382
"""
383
Retrieve planner overrides for the current user.
384
385
Returns:
386
Paginated list of PlannerOverride objects
387
"""
388
```
389
390
### Poll Operations
391
392
Create and manage polls.
393
394
```python { .api }
395
def create_poll(self, polls: list, **kwargs) -> Poll:
396
"""
397
Create a new poll for the current user.
398
399
Parameters:
400
- polls: List of poll dictionaries, each with 'question' key
401
402
Returns:
403
Poll object
404
"""
405
406
def get_poll(self, poll, **kwargs) -> Poll:
407
"""
408
Get a single poll based on poll ID.
409
410
Parameters:
411
- poll: Poll object or ID
412
413
Returns:
414
Poll object
415
"""
416
417
def get_polls(self, **kwargs) -> PaginatedList[Poll]:
418
"""
419
Return paginated list of polls for the current user.
420
421
Returns:
422
Paginated list of Poll objects
423
"""
424
```
425
426
### Additional Content Operations
427
428
Access various Canvas content types.
429
430
```python { .api }
431
def get_eportfolio(self, eportfolio, **kwargs) -> EPortfolio:
432
"""
433
Get an eportfolio by ID.
434
435
Parameters:
436
- eportfolio: EPortfolio object or ID
437
438
Returns:
439
EPortfolio object
440
"""
441
442
def get_epub_exports(self, **kwargs) -> PaginatedList[CourseEpubExport]:
443
"""
444
Return list of epub exports for associated course.
445
446
Returns:
447
Paginated list of CourseEpubExport objects
448
"""
449
450
def get_comm_messages(self, user, **kwargs) -> PaginatedList[CommMessage]:
451
"""
452
Retrieve paginated list of messages sent to a user.
453
454
Parameters:
455
- user: User object or ID
456
457
Returns:
458
Paginated list of CommMessage objects
459
"""
460
461
def get_account_calendars(self, **kwargs) -> PaginatedList[AccountCalendar]:
462
"""
463
Return paginated list of account calendars available to user.
464
465
Returns:
466
Paginated list of AccountCalendar objects
467
"""
468
469
def get_user_participants(self, appointment_group, **kwargs) -> PaginatedList[User]:
470
"""
471
List user participants in appointment group.
472
473
Parameters:
474
- appointment_group: AppointmentGroup object or ID
475
476
Returns:
477
Paginated list of User objects
478
"""
479
480
def get_group_participants(self, appointment_group, **kwargs) -> PaginatedList[Group]:
481
"""
482
List student group participants in appointment group.
483
484
Parameters:
485
- appointment_group: AppointmentGroup object or ID
486
487
Returns:
488
Paginated list of Group objects
489
"""
490
```
491
492
### Utility Operations
493
494
Additional utility functions for Canvas operations.
495
496
```python { .api }
497
def get_activity_stream_summary(self, **kwargs) -> dict:
498
"""Return summary of current user's global activity stream."""
499
500
def get_brand_variables(self, **kwargs) -> dict:
501
"""Get account brand variables."""
502
503
def get_todo_items(self, **kwargs) -> PaginatedList[Todo]:
504
"""Return current user's list of todo items."""
505
506
def get_upcoming_events(self, **kwargs) -> dict:
507
"""Return current user's upcoming events."""
508
509
def graphql(self, query: str, variables: dict = None, **kwargs) -> dict:
510
"""
511
Make a GraphQL formatted request to Canvas.
512
513
Parameters:
514
- query: The GraphQL query to execute as a string
515
- variables: The variable values required by the query
516
517
Returns:
518
Dictionary with GraphQL response
519
"""
520
```
521
522
### Progress Tracking
523
524
Monitor long-running operations.
525
526
```python { .api }
527
def get_progress(self, progress, **kwargs) -> Progress:
528
"""Get a specific progress object for monitoring operations."""
529
```
530
531
### JWT Operations
532
533
Create and refresh JSON Web Tokens for Canvas services.
534
535
```python { .api }
536
def create_jwt(self, **kwargs) -> JWT:
537
"""Create a unique JWT to use with other Canvas services."""
538
539
def refresh_jwt(self, jwt, **kwargs) -> JWT:
540
"""
541
Refresh a JWT for reuse with other Canvas services.
542
543
Parameters:
544
- jwt: An existing JWT string or JWT object to refresh
545
546
Returns:
547
New JWT object
548
"""
549
```
550
551
## Usage Examples
552
553
### Basic Setup and Course Access
554
555
```python
556
from canvasapi import Canvas
557
558
# Initialize Canvas connection
559
canvas = Canvas("https://canvas.instructure.com", "your-access-token")
560
561
# Get current user info
562
user = canvas.get_current_user()
563
print(f"Logged in as: {user.name}")
564
565
# Get all courses for current user
566
courses = canvas.get_courses()
567
for course in courses:
568
print(f"Course: {course.name} (ID: {course.id})")
569
570
# Get specific course by ID
571
course = canvas.get_course(12345)
572
print(f"Course name: {course.name}")
573
```
574
575
### Communication Example
576
577
```python
578
# Create a new conversation
579
recipients = ['123', '456', 'course_789'] # User IDs and course ID
580
conversation = canvas.create_conversation(
581
recipients=recipients,
582
body="Hello everyone! This is a test message.",
583
subject="Test Message"
584
)
585
586
# Get unread conversation count
587
unread_info = canvas.conversations_unread_count()
588
print(f"Unread conversations: {unread_info['unread_count']}")
589
590
# Mark all conversations as read
591
canvas.conversations_mark_all_as_read()
592
```
593
594
### GraphQL Example
595
596
```python
597
# Execute a GraphQL query
598
query = """
599
query GetCourse($courseId: ID!) {
600
course(id: $courseId) {
601
name
602
enrollmentsConnection {
603
nodes {
604
user {
605
name
606
}
607
}
608
}
609
}
610
}
611
"""
612
613
variables = {"courseId": "12345"}
614
result = canvas.graphql(query, variables)
615
print(result)
616
```