CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-canvasapi

API wrapper for the Canvas LMS

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

account-administration.mddocs/

Account Administration

Account management, user creation, role administration, SIS imports, and institutional-level operations. Comprehensive administrative functionality for Canvas account management.

Capabilities

User Management

Create, manage, and administer user accounts across the institution.

class Account(CanvasObject):
    def create_user(self, user: dict, **kwargs) -> User:
        """
        Create a new user account.
        
        Parameters:
        - user: Dictionary with user attributes:
            - name: User's full name (required)
            - short_name: User's display name
            - sortable_name: Name for sorting (Last, First)
            - time_zone: User's time zone
            - locale: User's locale/language
            - birthdate: User's birthdate
            - terms_of_use: Whether user agreed to terms
            - skip_registration: Skip email verification
        - pseudonym: Dictionary with login information:
            - unique_id: Login ID (username/email)
            - password: User password
            - sis_user_id: SIS user identifier
            - integration_id: Integration identifier
            - send_confirmation: Send confirmation email
        - communication_channel: Dictionary with communication channel:
            - type: Channel type ('email', 'sms')
            - address: Email address or phone number
            - confirmation_url: Confirmation URL template
            - skip_confirmation: Skip confirmation process
        - force_validations: Force validation of user data
        - enable_sis_reactivation: Enable SIS reactivation
        
        Returns:
        User object
        """
    
    def get_users(self, **kwargs) -> PaginatedList[User]:
        """
        List users in the account.
        
        Parameters:
        - search_term: Search term for user names or emails
        - enrollment_type: Filter by enrollment type
        - include: Additional data ('email', 'enrollments', 'locked', 'avatar_url', 'bio', 'custom_links')
        - user_ids: Specific user IDs to retrieve
        - user_id: Single user ID to retrieve
        - sort: Sort field ('username', 'last_login', 'email', 'sis_id')
        - order: Sort order ('asc', 'desc')
        
        Returns:
        Paginated list of User objects
        """
    
    def delete_user(self, user, **kwargs) -> User:
        """
        Delete a user from the account.
        
        Parameters:
        - user: User object or user ID
        
        Returns:
        Deleted User object
        """
    
    def create_user_login(self, user, login: dict, **kwargs) -> Login:
        """
        Create a login for an existing user.
        
        Parameters:
        - user: User object or user ID
        - login: Dictionary with login attributes:
            - unique_id: Login ID
            - password: Login password
            - sis_user_id: SIS user identifier
            - integration_id: Integration identifier
            - authentication_provider_id: Authentication provider ID
        
        Returns:
        Login object
        """

Course Management

Create and manage courses at the account level.

def create_course(self, **kwargs) -> Course:
    """
    Create a new course.
    
    Parameters:
    - account_id: Account ID for the course
    - course: Dictionary with course attributes:
        - name: Course name
        - course_code: Course code
        - start_at: Course start date
        - end_at: Course end date
        - license: Course license
        - is_public: Whether course is public
        - is_public_to_auth_users: Whether course is public to authenticated users
        - public_syllabus: Whether syllabus is public
        - public_syllabus_to_auth: Whether syllabus is public to authenticated users
        - public_description: Public course description
        - allow_student_wiki_edits: Allow students to edit wiki
        - allow_wiki_comments: Allow wiki comments
        - allow_student_forum_attachments: Allow student forum attachments
        - open_enrollment: Allow open enrollment
        - self_enrollment: Allow self-enrollment
        - restrict_enrollments_to_course_dates: Restrict enrollments to course dates
        - term_id: Enrollment term ID
        - sis_course_id: SIS course identifier
        - integration_id: Integration identifier
        - hide_final_grades: Hide final grades
        - apply_assignment_group_weights: Apply assignment group weights
        - time_zone: Course time zone
        - blueprint: Whether course is a blueprint
    - offer: Whether to offer the course immediately
    - enroll_me: Whether to enroll the creating user
    - enable_sis_reactivation: Enable SIS reactivation
    
    Returns:
    Course object
    """

def get_courses(self, **kwargs) -> PaginatedList[Course]:
    """
    List courses in the account.
    
    Parameters:
    - with_enrollments: Include only courses with enrollments
    - enrollment_type: Filter by enrollment type
    - published: Filter by published status
    - completed: Filter by completed status
    - blueprint: Filter blueprint courses
    - blueprint_associated: Filter courses associated with blueprints
    - by_teachers: Filter by teacher user IDs
    - by_subaccounts: Filter by subaccount IDs
    - hide_enrollmentless_courses: Hide courses without enrollments
    - state: Filter by workflow state
    - enrollment_term_id: Filter by enrollment term
    - search_term: Search term for course names/codes
    - include: Additional data ('needs_grading_count', 'syllabus_body', 'public_description', 'total_scores', 'current_grading_period_scores', 'term', 'account', 'course_progress', 'sections', 'storage_quota_used_mb', 'total_students', 'passback_status', 'favorites', 'teachers', 'observed_users', 'tabs')
    - sort: Sort field ('course_name', 'sis_course_id', 'teacher', 'account_name')
    - order: Sort order ('asc', 'desc')
    
    Returns:
    Paginated list of Course objects
    """

Subaccount Management

Create and manage account hierarchies.

def create_subaccount(self, account: dict, **kwargs) -> Account:
    """
    Create a subaccount.
    
    Parameters:
    - account: Dictionary with account attributes:
        - name: Account name (required)
        - sis_account_id: SIS account identifier
        - default_time_zone: Default time zone
        - default_storage_quota_mb: Default storage quota in MB
        - default_user_storage_quota_mb: Default user storage quota in MB
        - default_group_storage_quota_mb: Default group storage quota in MB
    
    Returns:
    Account object (subaccount)
    """

def get_sub_accounts(self, **kwargs) -> PaginatedList[Account]:
    """
    List subaccounts.
    
    Parameters:
    - recursive: Include all descendant accounts
    
    Returns:
    Paginated list of Account objects
    """

Admin User Management

Manage administrative users and their permissions.

def create_admin(self, user_id: int, **kwargs) -> Admin:
    """
    Create an admin user.
    
    Parameters:
    - user_id: ID of user to make admin
    - role: Admin role name
    - role_id: Admin role ID (alternative to role name)
    - send_confirmation: Send confirmation email
    
    Returns:
    Admin object
    """

def get_admins(self, **kwargs) -> PaginatedList[Admin]:
    """
    List account admins.
    
    Parameters:
    - user_id: Filter by specific user ID
    
    Returns:
    Paginated list of Admin objects
    """

def delete_admin(self, user_id: int, **kwargs) -> Admin:
    """
    Remove admin privileges from a user.
    
    Parameters:
    - user_id: ID of user to remove admin privileges from
    - role: Admin role to remove
    - role_id: Admin role ID to remove
    
    Returns:
    Deleted Admin object
    """

Role Management

Create and manage custom roles and permissions.

def create_role(self, **kwargs) -> Role:
    """
    Create a new role.
    
    Parameters:
    - label: Role name (required)
    - role: Base role to inherit from
    - permissions: Dictionary of permissions to enable/disable
    - base_role_type: Base role type ('AccountMembership', 'StudentEnrollment', 'TeacherEnrollment', etc.)
    
    Returns:
    Role object
    """

def get_roles(self, **kwargs) -> PaginatedList[Role]:
    """
    List roles in the account.
    
    Parameters:
    - account_id: Account ID to list roles for
    - state: Filter by role state ('active', 'inactive')
    - show_inherited: Show inherited roles
    
    Returns:
    Paginated list of Role objects
    """

def activate_role(self, role, **kwargs) -> Role:
    """
    Activate a role.
    
    Parameters:
    - role: Role object or role ID
    
    Returns:
    Activated Role object
    """

def deactivate_role(self, role, **kwargs) -> Role:
    """
    Deactivate a role.
    
    Parameters:
    - role: Role object or role ID
    
    Returns:
    Deactivated Role object
    """

Authentication Providers

Manage authentication methods and SSO integrations.

def add_authentication_providers(self, **kwargs) -> AuthenticationProvider:
    """
    Add an authentication provider.
    
    Parameters:
    - auth_type: Authentication type ('cas', 'ldap', 'saml', 'facebook', 'github', 'google', 'linkedin', 'microsoft', 'openid_connect', 'twitter')
    - auth_host: Authentication host
    - auth_filter: Authentication filter
    - auth_over_tls: Use authentication over TLS
    - auth_base: Authentication base
    - auth_username: Authentication username
    - auth_password: Authentication password
    - identifier_format: SAML identifier format
    - certificate_fingerprint: Certificate fingerprint
    - requested_authn_context: Requested authentication context
    - sig_alg: Signature algorithm
    - settings: Provider-specific settings
    
    Returns:
    AuthenticationProvider object
    """

def get_authentication_providers(self, **kwargs) -> PaginatedList[AuthenticationProvider]:
    """
    List authentication providers.
    
    Returns:
    Paginated list of AuthenticationProvider objects
    """

SIS Integration

Manage Student Information System imports and data synchronization.

def create_sis_import(self, **kwargs) -> SisImport:
    """
    Create a SIS import.
    
    Parameters:
    - import_type: Import type
    - attachment: File attachment for import
    - batch_mode: Enable batch mode
    - batch_mode_term_id: Term ID for batch mode
    - multi_term_batch_mode: Enable multi-term batch mode
    - skip_deletes: Skip delete operations
    - override_sis_stickiness: Override SIS stickiness
    - add_sis_stickiness: Add SIS stickiness
    - clear_sis_stickiness: Clear SIS stickiness
    - diffing_data_set_identifier: Data set identifier for diffing
    - diffing_remaster_data_set: Remaster data set for diffing
    
    Returns:
    SisImport object
    """

def get_sis_imports(self, **kwargs) -> PaginatedList[SisImport]:
    """
    List SIS imports for the account.
    
    Parameters:
    - created_since: Filter by creation date
    - created_before: Filter by creation date
    - workflow_state: Filter by workflow state
    
    Returns:
    Paginated list of SisImport objects
    """

def abort_sis_import(self, sis_import, **kwargs) -> SisImport:
    """
    Abort a running SIS import.
    
    Parameters:
    - sis_import: SisImport object or import ID
    
    Returns:
    Aborted SisImport object
    """

Enrollment Terms

Manage academic terms and grading periods.

def create_enrollment_term(self, **kwargs) -> EnrollmentTerm:
    """
    Create an enrollment term.
    
    Parameters:
    - enrollment_term: Dictionary with term attributes:
        - name: Term name (required)
        - start_at: Term start date
        - end_at: Term end date
        - sis_term_id: SIS term identifier
        - overrides: Date overrides for different enrollment types
    
    Returns:
    EnrollmentTerm object
    """

def get_enrollment_terms(self, **kwargs) -> PaginatedList[EnrollmentTerm]:
    """
    List enrollment terms.
    
    Parameters:
    - workflow_state: Filter by workflow state
    - include: Additional data ('overrides')
    
    Returns:
    Paginated list of EnrollmentTerm objects
    """

def create_grading_period(self, **kwargs) -> GradingPeriod:
    """
    Create a grading period.
    
    Parameters:
    - grading_periods: List of grading period dictionaries:
        - title: Grading period title
        - start_date: Start date
        - end_date: End date
        - close_date: Close date
        - weight: Weight for weighted grading
    
    Returns:
    GradingPeriod object
    """

def get_grading_periods(self, **kwargs) -> PaginatedList[GradingPeriod]:
    """List grading periods for the account."""

Reports and Analytics

Generate and access account-level reports and analytics.

def create_report(self, report_type: str, **kwargs) -> AccountReport:
    """
    Create an account report.
    
    Parameters:
    - report_type: Type of report to generate
    - parameters: Report-specific parameters
    - start_at: Report start date
    - end_at: Report end date
    
    Returns:
    AccountReport object
    """

def get_reports(self, **kwargs) -> PaginatedList[AccountReport]:
    """
    List available reports for the account.
    
    Returns:
    Paginated list of AccountReport objects
    """

def get_report_status(self, report_type: str, report_id: int, **kwargs) -> AccountReport:
    """
    Get status of a specific report.
    
    Parameters:
    - report_type: Report type
    - report_id: Report ID
    
    Returns:
    AccountReport object with current status
    """

Feature Management

Manage Canvas features and feature flags at the account level.

def get_features(self, **kwargs) -> PaginatedList[Feature]:
    """
    List features available to the account.
    
    Returns:
    Paginated list of Feature objects
    """

def get_feature_flag(self, feature, **kwargs) -> FeatureFlag:
    """
    Get feature flag status.
    
    Parameters:
    - feature: Feature name or Feature object
    
    Returns:
    FeatureFlag object
    """

def set_feature_flag(self, feature, state: str, **kwargs) -> FeatureFlag:
    """
    Set feature flag state.
    
    Parameters:
    - feature: Feature name or Feature object
    - state: Feature state ('off', 'allowed', 'on')
    
    Returns:
    FeatureFlag object
    """

Usage Examples

Creating and Managing Users

from canvasapi import Canvas

canvas = Canvas("https://canvas.example.com", "your-token")
account = canvas.get_account(1)  # Root account

# Create a new user with login credentials
new_user = account.create_user(
    user={
        'name': 'John Smith',
        'short_name': 'John',
        'sortable_name': 'Smith, John',
        'time_zone': 'America/New_York',
        'locale': 'en'
    },
    pseudonym={
        'unique_id': 'jsmith@university.edu',
        'password': 'secure_password_123',
        'sis_user_id': 'SIS123456',
        'send_confirmation': True
    },
    communication_channel={
        'type': 'email',
        'address': 'jsmith@university.edu',
        'skip_confirmation': False
    }
)

print(f"Created user: {new_user.name} (ID: {new_user.id})")

# Search for users
users = account.get_users(
    search_term='smith',
    include=['email', 'enrollments'],
    sort='last_login',
    order='desc'
)

for user in users:
    print(f"User: {user.name} ({user.login_id})")
    print(f"Last login: {user.last_login}")

# Create additional login for existing user
additional_login = account.create_user_login(
    user=new_user,
    login={
        'unique_id': 'john.smith',
        'sis_user_id': 'ALT_SIS_123456'
    }
)

Course Creation and Management

# Create a new course
new_course = account.create_course(
    course={
        'name': 'Introduction to Data Science',
        'course_code': 'CS 301',
        'start_at': '2024-01-15T00:00:00Z',
        'end_at': '2024-05-15T23:59:59Z',
        'time_zone': 'America/New_York',
        'sis_course_id': 'CS301_SP2024',
        'public_syllabus': True,
        'allow_student_wiki_edits': True,
        'term_id': spring_term.id
    },
    offer=True,  # Make course available immediately
    enroll_me=True  # Enroll creating user as teacher
)

# Get courses with filtering
active_courses = account.get_courses(
    with_enrollments=True,
    published=True,
    state=['available'],
    include=['needs_grading_count', 'term', 'teachers'],
    sort='course_name'
)

for course in active_courses:
    print(f"Course: {course.name} ({course.course_code})")
    print(f"Term: {course.term['name']}")
    print(f"Enrollments: {course.total_students}")

Role and Permission Management

# Create a custom role
custom_role = account.create_role(
    label='Course Assistant',
    base_role_type='TaEnrollment',
    permissions={
        'read_course_content': 'enable',
        'read_course_list': 'enable', 
        'read_question_banks': 'enable',
        'read_reports': 'disable',
        'manage_grades': 'enable',
        'post_to_forum': 'enable',
        'moderate_forum': 'disable',
        'send_messages': 'enable',
        'send_messages_all': 'disable'
    }
)

# List all roles
roles = account.get_roles(show_inherited=True)
for role in roles:
    print(f"Role: {role.label} (Base: {role.base_role_type})")

# Create admin user
admin_user = account.create_admin(
    user_id=new_user.id,
    role='Account Admin',
    send_confirmation=True
)

print(f"Created admin: {admin_user.user['name']}")

# List current admins
admins = account.get_admins()
for admin in admins:
    print(f"Admin: {admin.user['name']} (Role: {admin.role})")

SIS Import Management

# Create SIS import
sis_import = account.create_sis_import(
    import_type='instructure_csv',
    # attachment would be provided separately
    batch_mode=True,
    skip_deletes=False,
    override_sis_stickiness=False
)

print(f"Started SIS import: {sis_import.id}")
print(f"Status: {sis_import.workflow_state}")

# Monitor import progress
import time
while sis_import.workflow_state in ['created', 'importing']:
    time.sleep(30)  # Wait 30 seconds
    sis_import = account.get_sis_import(sis_import.id)
    print(f"Import progress: {sis_import.progress}%")

if sis_import.workflow_state == 'imported':
    print("Import completed successfully!")
    print(f"Processed: {sis_import.data}")
elif sis_import.workflow_state == 'failed_with_messages':
    print("Import failed with errors:")
    for error in sis_import.processing_errors:
        print(f"  Error: {error}")

# List recent imports
recent_imports = account.get_sis_imports(
    created_since='2024-01-01T00:00:00Z',
    workflow_state=['imported', 'failed']
)

for import_obj in recent_imports:
    print(f"Import {import_obj.id}: {import_obj.workflow_state} ({import_obj.created_at})")

Term and Grading Period Management

# Create enrollment terms
spring_term = account.create_enrollment_term(
    enrollment_term={
        'name': 'Spring 2024',
        'start_at': '2024-01-15T00:00:00Z',
        'end_at': '2024-05-15T23:59:59Z',
        'sis_term_id': 'SP2024'
    }
)

fall_term = account.create_enrollment_term(
    enrollment_term={
        'name': 'Fall 2024',
        'start_at': '2024-08-15T00:00:00Z',
        'end_at': '2024-12-15T23:59:59Z',
        'sis_term_id': 'FA2024'
    }
)

# Create grading periods for the term
grading_periods = account.create_grading_period(
    grading_periods=[
        {
            'title': 'First Quarter',
            'start_date': '2024-01-15',
            'end_date': '2024-03-15',
            'close_date': '2024-03-22',
            'weight': 25
        },
        {
            'title': 'Second Quarter', 
            'start_date': '2024-03-16',
            'end_date': '2024-05-15',
            'close_date': '2024-05-22',
            'weight': 25
        }
    ]
)

# List all terms
terms = account.get_enrollment_terms(include=['overrides'])
for term in terms:
    print(f"Term: {term.name} ({term.start_at} - {term.end_at})")

Report Generation

# Generate student enrollment report
enrollment_report = account.create_report(
    report_type='student_assignment_outcome_map_csv',
    parameters={
        'enrollment_term_id': spring_term.id,
        'include_deleted': False
    }
)

# Generate course usage report
usage_report = account.create_report(
    report_type='course_storage_csv',
    start_at='2024-01-01T00:00:00Z',
    end_at='2024-12-31T23:59:59Z'
)

# Check report status
while usage_report.workflow_state == 'running':
    time.sleep(60)  # Wait 1 minute
    usage_report = account.get_report_status('course_storage_csv', usage_report.id)
    print(f"Report progress: {usage_report.progress}%")

if usage_report.workflow_state == 'complete':
    print(f"Report completed: {usage_report.file_url}")
    # Download report file
    import requests
    response = requests.get(usage_report.file_url)
    with open('course_usage_report.csv', 'wb') as f:
        f.write(response.content)

Install with Tessl CLI

npx tessl i tessl/pypi-canvasapi

docs

account-administration.md

assignments-grading.md

communication.md

content-management.md

course-management.md

index.md

main-client.md

quizzes-assessments.md

user-management.md

tile.json