lms.djangoapps.course_api package

Contents

lms.djangoapps.course_api package#

Subpackages#

Submodules#

lms.djangoapps.course_api.api module#

Course API

lms.djangoapps.course_api.api.course_detail(request, username, course_key)#

Return a single course identified by course_key.

The course must be visible to the user identified by username and the logged-in user should have permission to view courses available to that user.

Parameters:
  • request (HTTPRequest) – Used to identify the logged-in user and to instantiate the course module to retrieve the course about description

  • username (string) – The name of the user `requesting_user would like to be identified as.

  • course_key (CourseKey) – Identifies the course of interest

Return value:

CourseOverview object representing the requested course

lms.djangoapps.course_api.api.get_course_members(course_key)#

Returns a dict containing all users with access to a course through CourseEnrollment and CourseAccessRole models.

User information includes id, email, username, name, enrollment mode and role list.

This API is limited and will only work for courses with less than a configurable number of active enrollments (managed through settings.COURSE_MEMBER_API_ENROLLMENT_LIMIT, and the default value is 1000). More than that and the method will raise a OverEnrollmentLimitException exception.

This method works by querying the CourseEnrollment and CourseAccessRole models, prefetching user information and then joining results in Python using dictionaries. This approach was choosen to avoid database heavy queries (such as DISTINCT and COUNT) in the CourseEnrollment table, which would take too long to complete in a request lifecycle.

The main concern with this approach is the dataset size and resource usage since this method returns all enrollments without pagination. We’re using a conservative number on the COURSE_MEMBER_API_ENROLLMENT_LIMIT setting to avoid any issues.

Examples

  • Get all course members:

    get_course_members(course_key)

Parameters:

course_key (CourseKey) – CourseKey to retrieve student data.

Returns:

A dictionary with the following format:
{
“user_id”: {

“id”: 12, “username”: “jonh5000”, “email”: “jonh@example.com”, “name”: “Jonh Doe”, “enrollment_mode”: “verified”, “roles”: [

”student”, “instructor”, “staff”,

]

}

}

Return type:

dict

lms.djangoapps.course_api.api.get_course_run_url(request, course_id)#

Get the URL to a course run.

Parameters:
  • request – the request object

  • course_id (string) – the course id of the course

Returns:

the URL to the course run associated with course_id

Return type:

(string)

lms.djangoapps.course_api.api.get_due_dates(request, course_key, user)#

Get due date information for a user for blocks in a course.

Parameters:
  • request – the request object

  • course_key (CourseKey) – the CourseKey for the course

  • user – the user object for which we want due date information

Returns:

a list of dictionaries containing due date information
keys:

name: the display name of the block url: the deep link to the block date: the due date for the block

Return type:

due_dates (list)

lms.djangoapps.course_api.api.get_effective_user(requesting_user, target_username)#

Get the user we want to view information on behalf of.

lms.djangoapps.course_api.api.list_course_keys(request, username, role)#

Yield all available CourseKeys for the user having the given role.

The courses returned include those for which the user identified by username has the given role. Additionally, the logged in user should have permission to view courses available to that user.

Note: This function does not use branding to determine courses.

Parameters:
  • request (HTTPRequest) – Used to identify the logged-in user and to instantiate the course module to retrieve the course about description

  • username (string) – The name of the user the logged-in user would like to be identified as

Keyword Arguments:

role (string) – Course keys are filtered such that only those for which the user has the specified role are returned.

Return value:

Yield CourseKey objects representing the collection of courses.

lms.djangoapps.course_api.api.list_courses(request, username, org=None, filter_=None, search_term=None, permissions=None, active_only=False, course_keys=None, mobile_search=False)#

Yield all available courses.

The courses returned are all be visible to the user identified by username and the logged in user should have permission to view courses available to that user.

Parameters:
  • request (HTTPRequest) – Used to identify the logged-in user and to instantiate the course module to retrieve the course about description

  • username (string) – The name of the user the logged-in user would like to be identified as

Keyword Arguments:
  • org (string) – If specified, visible CourseOverview objects are filtered such that only those belonging to the organization with the provided org code (e.g., “HarvardX”) are returned. Case-insensitive.

  • filter (dict) – If specified, visible CourseOverview objects are filtered by the given key-value pairs.

  • search_term (string) – Search term to filter courses (used by ElasticSearch).

  • permissions (list[str]) – If specified, it filters visible CourseOverview objects by checking if each permission specified is granted for the username.

  • active_only (bool) – Optional parameter that enables fetching active courses only.

  • course_keys (list[str]) – If specified, it filters visible CourseOverview objects by the course keys (ids) provided

  • mobile_search (bool) – Optional parameter that limits the number of returned courses to MOBILE_SEARCH_COURSE_LIMIT.

Return value:

Yield CourseOverview objects representing the collection of courses.

lms.djangoapps.course_api.exceptions module#

Course API custom exceptions

exception lms.djangoapps.course_api.exceptions.OverEnrollmentLimitException#

Bases: Exception

Exception used by get_course_members to signal when a course has more enrollments than the limit specified on settings.COURSE_MEMBER_API_ENROLLMENT_LIMIT.

lms.djangoapps.course_api.forms module#

Course API forms

class lms.djangoapps.course_api.forms.CourseDetailGetForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None, bound_field_class=None)#

Bases: UsernameValidatorMixin, Form

A form to validate query parameters in the course detail endpoint

base_fields = {'course_key': <django.forms.fields.CharField object>, 'username': <django.forms.fields.CharField object>}#
clean_course_key()#

Ensure a valid course_key was provided.

declared_fields = {'course_key': <django.forms.fields.CharField object>, 'username': <django.forms.fields.CharField object>}#
property media#

Return all media required to render the widgets on this form.

class lms.djangoapps.course_api.forms.CourseIdListGetForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None, bound_field_class=None)#

Bases: UsernameValidatorMixin, Form

A form to validate query parameters in the course list retrieval endpoint

base_fields = {'role': <django.forms.fields.CharField object>, 'username': <django.forms.fields.CharField object>}#
declared_fields = {'role': <django.forms.fields.CharField object>, 'username': <django.forms.fields.CharField object>}#
property media#

Return all media required to render the widgets on this form.

class lms.djangoapps.course_api.forms.CourseListGetForm(data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.utils.ErrorList'>, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None, bound_field_class=None)#

Bases: UsernameValidatorMixin, Form

A form to validate query parameters in the course list retrieval endpoint

base_fields = {'active_only': <openedx.core.djangoapps.util.forms.ExtendedNullBooleanField object>, 'course_keys': <openedx.core.djangoapps.util.forms.MultiValueField object>, 'mobile': <openedx.core.djangoapps.util.forms.ExtendedNullBooleanField object>, 'mobile_search': <openedx.core.djangoapps.util.forms.ExtendedNullBooleanField object>, 'org': <django.forms.fields.CharField object>, 'permissions': <openedx.core.djangoapps.util.forms.MultiValueField object>, 'search_term': <django.forms.fields.CharField object>, 'username': <django.forms.fields.CharField object>}#
clean()#

Return cleaned data, including additional filters.

clean_course_keys()#

Ensure valid course_keys were provided.

declared_fields = {'active_only': <openedx.core.djangoapps.util.forms.ExtendedNullBooleanField object>, 'course_keys': <openedx.core.djangoapps.util.forms.MultiValueField object>, 'mobile': <openedx.core.djangoapps.util.forms.ExtendedNullBooleanField object>, 'mobile_search': <openedx.core.djangoapps.util.forms.ExtendedNullBooleanField object>, 'org': <django.forms.fields.CharField object>, 'permissions': <openedx.core.djangoapps.util.forms.MultiValueField object>, 'search_term': <django.forms.fields.CharField object>, 'username': <django.forms.fields.CharField object>}#
class filter_type(param_name, field_name)#

Bases: tuple

field_name#

Alias for field number 1

param_name#

Alias for field number 0

property media#

Return all media required to render the widgets on this form.

supported_filters = [('mobile', 'mobile_available')]#
class lms.djangoapps.course_api.forms.UsernameValidatorMixin#

Bases: object

Mixin class for validating the username parameter.

clean_username()#

Ensures the username is provided unless the request is made as an anonymous user.

lms.djangoapps.course_api.permissions module#

Course API Authorization functions

lms.djangoapps.course_api.permissions.can_view_courses_for_username(requesting_user, target_username)#

Determine whether requesting_user has permission to view courses available to the user identified by target_username.

Parameters:
  • requesting_user (User) – The user requesting permission to view another

  • target_username (string) – The name of the user requesting_user would like to access.

Return value:
Boolean:

True if requesting_user is authorized to view courses as target_username. Otherwise, False

Raises:

TypeError if target_username is empty or None.

lms.djangoapps.course_api.serializers module#

Course API Serializers. Representing course catalog data

class lms.djangoapps.course_api.serializers.CourseDetailSerializer(*args, **kwargs)#

Bases: CourseSerializer

Serializer for Course objects providing additional details about the course.

This serializer makes additional database accesses (to the modulestore) and returns more data (including ‘overview’ text). Therefore, for performance and bandwidth reasons, it is expected that this serializer is used only when serializing a single course, and not for serializing a list of courses.

get_overview(course_overview)#

Get the representation for SerializerMethodField overview

to_representation(instance)#

Get the certificate_available_date in response if the certificates.auto_certificate_generation waffle switch is enabled

Get the ‘is_enrolled’ in response if ‘username’ is in query params, user is staff, superuser, or user is authenticated and the has the same ‘username’ as the ‘username’ in the query params.

class lms.djangoapps.course_api.serializers.CourseKeySerializer(*args, **kwargs)#

Bases: BaseSerializer

Serializer that takes a CourseKey and serializes it to a string course_id.

to_representation(instance)#

Transform the outgoing native value into primitive data.

class lms.djangoapps.course_api.serializers.CourseSerializer(*args, **kwargs)#

Bases: Serializer

Serializer for Course objects providing minimal data about the course. Compare this with CourseDetailSerializer.

get_blocks_url(course_overview)#

Get the representation for SerializerMethodField blocks_url

get_hidden(course_overview)#

Get the representation for SerializerMethodField hidden Represents whether course is hidden in LMS

class lms.djangoapps.course_api.serializers.ImageSerializer(*args, **kwargs)#

Bases: Serializer

Collection of URLs pointing to images of various sizes.

The URLs will be absolute URLs with the host set to the host of the current request. If the values to be serialized are already absolute URLs, they will be unchanged.

lms.djangoapps.course_api.urls module#

Course API URLs

lms.djangoapps.course_api.views module#

Course API Views

class lms.djangoapps.course_api.views.CourseDetailView(**kwargs)#

Bases: DeveloperErrorViewMixin, RetrieveAPIView

Use Cases

Request details for a course

Example Requests

GET /api/courses/v1/courses/{course_key}/

Response Values

Body consists of the following fields:

  • effort: A textual description of the weekly hours of effort expected

    in the course.

  • end: Date the course ends, in ISO 8601 notation

  • enrollment_end: Date enrollment ends, in ISO 8601 notation

  • enrollment_start: Date enrollment begins, in ISO 8601 notation

  • id: A unique identifier of the course; a serialized representation

    of the opaque key identifying the course.

  • media: An object that contains named media items. Included here:
    • course_image: An image to show for the course. Represented as an object with the following fields:

      • uri: The location of the image

  • name: Name of the course

  • number: Catalog number of the course

  • org: Name of the organization that owns the course

  • overview: A possibly verbose HTML textual description of the course.

    Note: this field is only included in the Course Detail view, not the Course List view.

  • short_description: A textual description of the course

  • start: Date the course begins, in ISO 8601 notation

  • start_display: Readably formatted start of the course

  • start_type: Hint describing how start_display is set. One of:
    • “string”: manually set by the course author

    • “timestamp”: generated from the start timestamp

    • “empty”: no start date is specified

  • pacing: Course pacing. Possible values: instructor, self

  • certificate_available_date (optional): Date the certificate will be available,

    in ISO 8601 notation if the certificates.auto_certificate_generation waffle switch is enabled

Deprecated fields:

  • blocks_url: Used to fetch the course blocks

  • course_id: Course key (use ‘id’ instead)

Parameters:

username (optional):

The username of the specified user for whom the course data is being accessed. The username is not only required if the API is requested by an Anonymous user.

Returns

  • 200 on success with above fields.

  • 400 if an invalid parameter was sent or the username was not provided for an authenticated request.

  • 403 if a user who does not have permission to masquerade as another user specifies a username other than their own.

  • 404 if the course is not available or cannot be seen.

Example response:

{

“blocks_url”: “/api/courses/v1/blocks/?course_id=edX%2Fexample%2F2012_Fall”, “media”: {

“course_image”: {

“uri”: “/c4x/edX/example/asset/just_a_test.jpg”, “name”: “Course Image”

}

}, “description”: “An example course.”, “end”: “2015-09-19T18:00:00Z”, “enrollment_end”: “2015-07-15T00:00:00Z”, “enrollment_start”: “2015-06-15T00:00:00Z”, “course_id”: “edX/example/2012_Fall”, “name”: “Example Course”, “number”: “example”, “org”: “edX”, “overview: “<p>A verbose description of the course.</p>” “start”: “2015-07-17T12:00:00Z”, “start_display”: “July 17, 2015”, “start_type”: “timestamp”, “pacing”: “instructor”, “certificate_available_date”: “2015-08-14T00:00:00Z”

}

authentication_classes = (<class 'edx_rest_framework_extensions.auth.jwt.authentication.JwtAuthentication'>, <class 'openedx.core.lib.api.authentication.BearerAuthenticationAllowInactiveUser'>, <class 'edx_rest_framework_extensions.auth.session.authentication.SessionAuthenticationAllowInactiveUser'>)#
get_object()#

Return the requested course object, if the user has appropriate permissions.

permission_classes = ()#
serializer_class#

alias of CourseDetailSerializer

class lms.djangoapps.course_api.views.CourseIdListUserThrottle#

Bases: UserRateThrottle

Limit the number of requests users can make to the course list id API.

THROTTLE_RATES = {'staff': '40/minute', 'user': '20/minute'}#
allow_request(request, view)#

Implement the check to see if the request should be throttled.

On success calls throttle_success. On failure calls throttle_failure.

class lms.djangoapps.course_api.views.CourseIdListView(**kwargs)#

Bases: DeveloperErrorViewMixin, ListAPIView

Use Cases

Request a list of course IDs for all courses the specified user can access based on the provided parameters.

Example Requests

GET /api/courses/v1/courses_ids/

Response Values

Body comprises a list of course ids and pagination details.

Parameters

username (optional):

The username of the specified user whose visible courses we want to see.

role (required):

Course ids are filtered such that only those for which the user has the specified role are returned. Role can be “staff” or “instructor”. Case-insensitive.

Returns

  • 200 on success, with a list of course ids and pagination details

  • 400 if an invalid parameter was sent or the username was not provided for an authenticated request.

  • 403 if a user who does not have permission to masquerade as another user who specifies a username other than their own.

  • 404 if the specified user does not exist, or the requesting user does not have permission to view their courses.

Example response:

{
“results”:
[

“course-v1:edX+DemoX+Demo_Course”

],

“pagination”: {

“previous”: null, “num_pages”: 1, “next”: null, “count”: 1

}

}

class CourseIdListPageNumberPagination#

Bases: LazyPageNumberPagination

max_page_size = 1000#
authentication_classes = (<class 'edx_rest_framework_extensions.auth.jwt.authentication.JwtAuthentication'>, <class 'openedx.core.lib.api.authentication.BearerAuthenticationAllowInactiveUser'>, <class 'edx_rest_framework_extensions.auth.session.authentication.SessionAuthenticationAllowInactiveUser'>)#
filter_queryset(*args, **kwargs)#

No-op passthrough function purely for function-tracing (monitoring) purposes.

This should be called once per GET request.

get_paginated_response(*args, **kwargs)#

No-op passthrough function purely for function-tracing (monitoring) purposes.

This should be called only when the response is paginated. Two pages means two GET requests and one function call per request. Otherwise, if the whole response fits in one page, this function never gets called.

get_queryset()#

Returns CourseKeys for courses which the user has the provided role.

get_serializer(*args, **kwargs)#

No-op passthrough function purely for function-tracing (monitoring) purposes.

This should be called once per GET request.

paginate_queryset(*args, **kwargs)#

No-op passthrough function purely for function-tracing (monitoring) purposes.

This should be called once per GET request.

pagination_class#

alias of CourseIdListPageNumberPagination

permission_classes = (<class 'rest_framework.permissions.IsAuthenticated'>,)#
serializer_class#

alias of CourseKeySerializer

throttle_classes = (<class 'lms.djangoapps.course_api.views.CourseIdListUserThrottle'>,)#
class lms.djangoapps.course_api.views.CourseListUserThrottle#

Bases: UserRateThrottle

Limit the number of requests users can make to the course list API.

THROTTLE_RATES = {'staff': '40/minute', 'user': '20/minute'}#
allow_request(request, view)#

Implement the check to see if the request should be throttled.

On success calls throttle_success. On failure calls throttle_failure.

check_for_switches()#
class lms.djangoapps.course_api.views.CourseListView(**kwargs)#

Bases: DeveloperErrorViewMixin, ListAPIView

Use Cases

Request information on all courses visible to the specified user.

Example Requests

GET /api/courses/v1/courses/ POST /api/courses/v1/courses/

Response Values

Body comprises a list of objects as returned by CourseDetailView.

Parameters

search_term (optional):

Search term to filter courses (used by ElasticSearch).

username (optional):

The username of the specified user whose visible courses we want to see. The username is not required only if the API is requested by an Anonymous user.

org (optional):

If specified, visible CourseOverview objects are filtered such that only those belonging to the organization with the provided org code (e.g., “HarvardX”) are returned. Case-insensitive.

permissions (optional):

If specified, it filters visible CourseOverview objects by checking if each permission specified is granted for the username. Notice that Staff users are always granted permission to list any course.

active_only (optional):

If this boolean is specified, only the courses that have not ended or do not have any end date are returned. This is different from search_term because this filtering is done on CourseOverview and not ElasticSearch.

course_keys (optional):

If specified, it fetches the CourseOverview objects for the the specified course keys

mobile_search (bool):

Optional parameter that limits the number of returned courses to MOBILE_SEARCH_COURSE_LIMIT.

Returns

  • 200 on success, with a list of course discovery objects as returned by CourseDetailView.

  • 400 if an invalid parameter was sent or the username was not provided for an authenticated request.

  • 403 if a user who does not have permission to masquerade as another user specifies a username other than their own.

  • 404 if the specified user does not exist, or the requesting user does not have permission to view their courses.

Example response:

[
{

“blocks_url”: “/api/courses/v1/blocks/?course_id=edX%2Fexample%2F2012_Fall”, “media”: {

“course_image”: {

“uri”: “/c4x/edX/example/asset/just_a_test.jpg”, “name”: “Course Image”

}

}, “description”: “An example course.”, “end”: “2015-09-19T18:00:00Z”, “enrollment_end”: “2015-07-15T00:00:00Z”, “enrollment_start”: “2015-06-15T00:00:00Z”, “course_id”: “edX/example/2012_Fall”, “name”: “Example Course”, “number”: “example”, “org”: “edX”, “start”: “2015-07-17T12:00:00Z”, “start_display”: “July 17, 2015”, “start_type”: “timestamp”

}

]

Note

The POST /api/courses/v1/courses/ reads request.body for parameters, allowing for larger input than the query string.

class CourseListPageNumberPagination#

Bases: LazyPageNumberPagination

max_page_size = 100#
authentication_classes = (<class 'edx_rest_framework_extensions.auth.jwt.authentication.JwtAuthentication'>, <class 'openedx.core.lib.api.authentication.BearerAuthenticationAllowInactiveUser'>, <class 'edx_rest_framework_extensions.auth.session.authentication.SessionAuthenticationAllowInactiveUser'>)#
get_queryset()#

Yield courses visible to the user.

pagination_class#

alias of CourseListPageNumberPagination

permission_classes = ()#
post(request, *args, **kwargs)#

POST courses filter.

serializer_class#

alias of CourseSerializer

throttle_classes = (<class 'lms.djangoapps.course_api.views.CourseListUserThrottle'>,)#
class lms.djangoapps.course_api.views.LazyPageNumberPagination#

Bases: NamespacedPageNumberPagination

NamespacedPageNumberPagination that works with a LazySequence queryset.

The paginator cache uses @cached_property to cache the property values for count and num_pages. It assumes these won’t change, but in the case of a LazySequence, its count gets updated as we move through it. This class clears the cached property values before reporting results so they will be recalculated.

get_paginated_response(data)#

Annotate the response with pagination information

paginate_queryset(queryset, request, view=None)#

Paginate a queryset if required, either returning a page object, or None if pagination is not configured for this view.

This is copied verbatim from upstream with added function traces. encode/django-rest-framework

Module contents#

Course API