openedx.core.lib.api package#
Submodules#
openedx.core.lib.api.authentication module#
Common Authentication Handlers used across projects.
- class openedx.core.lib.api.authentication.BearerAuthentication#
Bases:
BaseAuthenticationBearerAuthentication backend using either django-oauth2-provider or ‘django-oauth-toolkit’
- allow_inactive_users = False#
- authenticate(request)#
Returns tuple (user, token) if access token authentication succeeds, returns None if the user did not try to authenticate using an access token, or raises an AuthenticationFailed (HTTP 401) if authentication fails.
- authenticate_credentials(access_token)#
Authenticate the request, given the access token.
Overrides base class implementation to discard failure if user is inactive.
- authenticate_header(request)#
Return a string to be used as the value of the WWW-Authenticate header in a 401 Unauthenticated response
- get_access_token(access_token)#
Return a valid access token stored by django-oauth-toolkit (DOT), or None if no matching token is found.
- www_authenticate_realm = 'api'#
- class openedx.core.lib.api.authentication.BearerAuthenticationAllowInactiveUser#
Bases:
BearerAuthenticationCurrently, is_active field on the user is coupled with whether or not the user has verified ownership of their claimed email address. Once is_active is decoupled from verified_email, we will no longer need this class override.
This class can be used for an OAuth2-accessible endpoint that allows users to access that endpoint without having their email verified. For example, this is used for mobile endpoints.
- allow_inactive_users = True#
- class openedx.core.lib.api.authentication.OAuth2Authentication#
Bases:
BearerAuthenticationCreating temperary class cause things outside of edx-platform need OAuth2Authentication. This will be removed when repos outside edx-platform import BearerAuthentiction instead.
- class openedx.core.lib.api.authentication.OAuth2AuthenticationAllowInactiveUser#
Bases:
BearerAuthenticationAllowInactiveUserCreating temperary class cause things outside of edx-platform need OAuth2Authentication. This will be removed when repos outside edx-platform import BearerAuthentiction instead.
openedx.core.lib.api.fields module#
Fields useful for edX API implementations.
- class openedx.core.lib.api.fields.AbsoluteURLField(*args, **kwargs)#
Bases:
URLFieldField that serializes values to absolute URLs based on the current request.
If the value to be serialized is already a URL, that value will returned.
- to_representation(value)#
Transform the outgoing native value into primitive data.
- class openedx.core.lib.api.fields.ExpandableField(*args, **kwargs)#
Bases:
FieldField that can dynamically use a more detailed serializer based on a user-provided “expand” parameter.
- Kwargs:
collapsed_serializer (Serializer): the serializer to use for a non-expanded representation. expanded_serializer (Serializer): the serializer to use for an expanded representation.
- to_representation(obj)#
Return a representation of the field that is either expanded or collapsed.
openedx.core.lib.api.mixins module#
Django Rest Framework view mixins.
openedx.core.lib.api.parsers module#
Custom DRF request parsers. These can be used by views to handle different content types, as specified by <Parser>.media_type.
To use these in an APIView, set <View>.parser_classes to a list including the desired parsers. See http://www.django-rest-framework.org/api-guide/parsers/ for details.
- class openedx.core.lib.api.parsers.MergePatchParser#
Bases:
JSONParserCustom parser to be used with the “merge patch” implementation (https://tools.ietf.org/html/rfc7396).
- media_type = 'application/merge-patch+json'#
- class openedx.core.lib.api.parsers.TypedFileUploadParser#
Bases:
FileUploadParserHandles upload of files, ensuring that the media type is supported, and that the uploaded filename matches the Content-type.
- Requirements:
The view must have an upload_media_types attribute which is a set (or other container) enumerating the mimetypes of the supported media formats
Example:
View.upload_media_types = {‘audio/mp3’, ‘audio/ogg’, ‘audio/wav’}
Content-type must be set to a supported type (as defined in View.upload_media_types above).
Example:
Content-type: audio/ogg
Content-disposition must include a filename with a valid extension for the specified Content-type.
Example:
Content-disposition: attachment; filename=”lecture-1.ogg”
- file_extensions = {'image/gif': {'.gif'}, 'image/jpeg': {'.jpeg', '.jpg'}, 'image/pjpeg': {'.jpeg', '.jpg'}, 'image/png': {'.png'}, 'image/svg': {'.svg'}}#
- media_type = '*/*'#
- parse(stream, media_type=None, parser_context=None)#
Parse the request, returning a DataAndFiles object with the data dict left empty, and the body of the request placed in files[‘file’].
openedx.core.lib.api.permissions module#
API library for Django REST Framework permissions-oriented workflows
- class openedx.core.lib.api.permissions.ApiKeyHeaderPermission#
Bases:
BasePermissionDjango REST Framework permissions class used to manage API Key integrations
Deprecated
- has_permission(request, view)#
Check for permissions by matching the configured API key and header Allow the request if and only if settings.EDX_API_KEY is set and the X-Edx-Api-Key HTTP header is present in the request and matches the setting.
- class openedx.core.lib.api.permissions.ApiKeyHeaderPermissionIsAuthenticated#
Bases:
ApiKeyHeaderPermission,IsAuthenticatedAllow someone to access the view if they have the API key OR they are authenticated. See ApiKeyHeaderPermission for more information how the API key portion is implemented.
- has_permission(request, view)#
Check for permissions by matching the configured API key and header Allow the request if and only if settings.EDX_API_KEY is set and the X-Edx-Api-Key HTTP header is present in the request and matches the setting.
- class openedx.core.lib.api.permissions.IsCourseStaffInstructor#
Bases:
BasePermissionPermission to check that user is a course instructor or staff of a master course given a course object or the user is a coach of the course itself.
- has_object_permission(request, view, obj)#
Return True if permission is granted, False otherwise.
- class openedx.core.lib.api.permissions.IsMasterCourseStaffInstructor#
Bases:
BasePermissionPermission to check that user is instructor or staff of the master course.
- has_permission(request, view)#
This method is assuming that a master_course_id parameter is available in the request as a GET parameter, a POST parameter or it is in the JSON payload included in the request. The reason is because this permission class is going to check if the user making the request is an instructor for the specified course.
- class openedx.core.lib.api.permissions.IsStaffOrOwner#
Bases:
BasePermissionPermission that allows access to admin users or the owner of an object. The owner is considered the User object represented by obj.user.
- has_object_permission(request, view, obj)#
Return True if permission is granted, False otherwise.
- has_permission(request, view)#
Return True if permission is granted, False otherwise.
openedx.core.lib.api.serializers module#
Serializers to be used in APIs.
- class openedx.core.lib.api.serializers.CollapsedReferenceSerializer(*args, **kwargs)#
Bases:
HyperlinkedModelSerializerSerializes arbitrary models in a collapsed format, with just an id and url.
- class openedx.core.lib.api.serializers.CourseKeyField(*args, **kwargs)#
Bases:
FieldSerializer field for a model CourseKey field.
- to_internal_value(data)#
Convert unicode to a course key.
- to_representation(data)#
Convert a course key to unicode.
- class openedx.core.lib.api.serializers.StatusSerializerWithUuid(*args, **kwargs)#
Bases:
StatusSerializerSerializer for the user task status, including uuid.
openedx.core.lib.api.test_utils module#
Helpers for API tests.
- class openedx.core.lib.api.test_utils.ApiTestCase(methodName='runTest')#
Bases:
TestCaseParent test case for API workflow coverage
- assertAllowedMethods(uri, expected_methods)#
Assert that the allowed methods for the given URI match the expected list
- assertAuthDisabled(method, uri)#
Assert that the Django rest framework does not interpret basic auth headers for views exposed to anonymous users as an attempt to authenticate.
- assertHttpBadRequest(response)#
Assert that the given response has the status code 400
- assertHttpCreated(response)#
Assert that the given response has the status code 201
- assertHttpForbidden(response)#
Assert that the given response has the status code 403
- assertHttpMethodNotAllowed(response)#
Assert that the given response has the status code 405
- assertHttpNotAuthorized(response)#
Assert that the given response has the status code 401
- assertHttpOK(response)#
Assert that the given response has the status code 200
- assertSelfReferential(obj)#
Assert that accessing the “url” entry in the given object returns the same object
- basic_auth(username, password)#
Returns a dictionary containing the http auth header with encoded username+password
- get_json(*args, **kwargs)#
Make a request with the given args and return the parsed JSON response
- request_with_auth(method, *args, **kwargs)#
Issue a request to the given URI with the API key header
- request_without_auth(method, *args, **kwargs)#
Issue a request to the given URI without the API key header. This may be useful if you’ll be calling an endpoint from javascript code and want to avoid exposing our API key.
openedx.core.lib.api.view_utils module#
Utilities related to API views
- exception openedx.core.lib.api.view_utils.DeveloperErrorResponseException(response)#
Bases:
ExceptionAn exception class that wraps a DRF Response object so that it does not need to be recreated when returning a response. Intended to be used with and by DeveloperErrorViewMixin.
- class openedx.core.lib.api.view_utils.DeveloperErrorViewMixin#
Bases:
objectA view mixin to handle common error cases other than validation failure (auth failure, method not allowed, etc.) by generating an error response conforming to our API conventions with a developer message.
- classmethod api_error(status_code, developer_message, error_code=None)#
- handle_exception(exc)#
Generalized helper method for managing specific API exception workflows
- class openedx.core.lib.api.view_utils.ExpandableFieldViewMixin#
Bases:
objectA view mixin to add expansion information to the serializer context for later use by an ExpandableField.
- get_serializer_context()#
Adds expand information from query parameters to the serializer context to support expandable fields.
- class openedx.core.lib.api.view_utils.LazySequence(iterable, est_len=None)#
Bases:
SequenceThis class provides an immutable Sequence interface on top of an existing iterable.
It is immutable, and accepts an estimated length in order to support __len__ without exhausting the underlying sequence
- class openedx.core.lib.api.view_utils.PaginatedAPIView(**kwargs)#
Bases:
APIViewAn APIView class enhanced with the pagination methods of GenericAPIView.
- get_paginated_response(data, *args, **kwargs)#
Return a paginated style Response object for the given output data.
- paginate_queryset(queryset)#
Return a single page of results, or None if pagination is disabled.
- property paginator#
The paginator instance associated with the view, or None.
- class openedx.core.lib.api.view_utils.RetrievePatchAPIView(**kwargs)#
Bases:
RetrieveModelMixin,UpdateModelMixin,GenericAPIViewConcrete view for retrieving and updating a model instance.
Like DRF’s RetrieveUpdateAPIView, but without PUT and with automatic validation errors in the edX format.
- get(request, *args, **kwargs)#
Retrieves the specified resource using the RetrieveModelMixin.
- get_object_or_none()#
Retrieve an object or return None if the object can’t be found.
NOTE: This replaces functionality that was removed in Django Rest Framework v3.1.
- patch(request, *args, **kwargs)#
Checks for validation errors, then updates the model using the UpdateModelMixin.
- openedx.core.lib.api.view_utils.add_serializer_errors(serializer, data, field_errors)#
Adds errors from serializer validation to field_errors. data is the original data to deserialize.
- openedx.core.lib.api.view_utils.build_api_error(message, **kwargs)#
Build an error dict corresponding to edX API conventions.
- Parameters:
message (string) – The string to use for developer and user messages. The user message will be translated, but for this to work message must have already been scraped. gettext_noop is useful for this.
**kwargs – format parameters for message
- openedx.core.lib.api.view_utils.clean_errors(error)#
DRF error messages are of type ErrorDetail and serialize out as such. We want to coerce the strings into the message only.
This cursively handles the nesting of errors.
- openedx.core.lib.api.view_utils.get_course_key(request, course_id=None)#
- openedx.core.lib.api.view_utils.require_post_params(required_params)#
View decorator that ensures the required POST params are present. If not, returns an HTTP response with status 400.
- Parameters:
required_params (list) – The required parameter keys.
- Returns:
HttpResponse
- openedx.core.lib.api.view_utils.validate_course_key(course_key_string: str) CourseKey#
Validate and parse a course_key string, if supported.
- Parameters:
course_key_string (str) – string course key to validate
- Returns:
validated course key
- Return type:
CourseKey
- Raises:
ValidationError – DRF Validation error in case the course key is invalid
- openedx.core.lib.api.view_utils.verify_course_exists(missing_course_error_message=None)#
A decorator to wrap a view function that takes course_key as a parameter.
- Raises:
An API error if the course_key is invalid, or if no CourseOverview exists for the given key. –
- openedx.core.lib.api.view_utils.view_auth_classes(is_user=False, is_authenticated=True)#
Function and class decorator that abstracts the authentication and permission checks for api views.
Module contents#
Package for common functionality shared across various APIs.