enterprise.api_client package#

Submodules#

enterprise.api_client.braze module#

API clients to communicate with Braze services.

class enterprise.api_client.braze.BrazeAPIClient#

Bases: BrazeClient

API client for calls to Braze.

create_recipient(user_email, lms_user_id, trigger_properties=None)#

Create a recipient object using the given user_email and lms_user_id. Identifies the given email address with any existing Braze alias records via the provided lms_user_id.

create_recipient_no_external_id(user_email)#

Create a Braze recipient dict identified only by an alias based on their email.

Generate a mailto link for the given emails.

enterprise.api_client.client module#

Base API clients to communicate with edx services.

class enterprise.api_client.client.APIClientMixin#

Bases: object

API client mixin.

API_BASE_URL = ''#
APPEND_SLASH = False#
get_api_url(path)#

Helper method to construct the API URL.

Parameters:

path (str) – the API endpoint path string.

class enterprise.api_client.client.BackendServiceAPIClient#

Bases: APIClientMixin

API client based on OAuthAPIClient to communicate with edx services.

Uses the backend service user to make requests.

class enterprise.api_client.client.NoAuthAPIClient#

Bases: APIClientMixin

API client based on requests.Session to communicate with edx services.

Used to call APIs which don’t require authentication.

get_health()#

Retrieve health details for the service.

Returns:

Response containing the service health.

Return type:

dict

class enterprise.api_client.client.UserAPIClient(user, expires_in=3600)#

Bases: APIClientMixin

API client based on requests.Session to communicate with edx services.

Requires user object to instantiate the client with the jwt token authentication.

connect()#

Connect to the REST API, authenticating with a JWT for the current user.

static refresh_token(func)#

Use this method decorator to ensure the JWT token is refreshed when needed.

token_is_expired()#

Return True if the JWT token has expired, False if not.

enterprise.api_client.discovery module#

Utilities to get details from the course catalog API.

class enterprise.api_client.discovery.CourseCatalogApiClient(user, site=None)#

Bases: UserAPIClient

The API client to make calls to the Catalog API.

APPEND_SLASH = True#
CATALOGS_COURSES_ENDPOINT = 'catalogs/{}/courses/'#
COURSES_ENDPOINT = 'courses'#
COURSE_RUNS_ENDPOINT = 'course_runs'#
DEFAULT_VALUE_SAFEGUARD = <object object>#
PROGRAMS_ENDPOINT = 'programs'#
PROGRAM_TYPES_ENDPOINT = 'program_types'#
SEARCH_ALL_ENDPOINT = 'search/all/'#
get_catalog_results(content_filter_query, query_params=None, traverse_pagination=False)#

Return results from the cache or discovery service’s search/all endpoint.

Parameters:
  • content_filter_query (dict) – query parameters used to filter catalog results.

  • query_params (dict) – query parameters used to paginate results.

  • traverse_pagination (bool) – True to return all results, False to return the paginated response. Defaults to False.

Returns:

Paginated response or all the records.

Return type:

dict

get_catalog_results_from_discovery(content_filter_query, query_params=None, traverse_pagination=False)#

Return results from the discovery service’s search/all endpoint.

get_course_and_course_run(course_run_id)#

Return the course and course run metadata for the given course run ID.

Parameters:

course_run_id (str) – The course run ID.

Returns:

The course metadata and the course run metadata.

Return type:

tuple

get_course_details(course_id)#

Return the details of a single course by id - not a course run id.

Parameters:

course_id (str) – The unique id for the course in question.

Returns:

Details of the course in question.

Return type:

dict

get_course_id(course_identifier)#

Return the course id for the given course identifier. The course_identifier may be a course id or a course run id; in either case the course id will be returned.

The ‘course id’ is the identifier for a course (ex. edX+DemoX) The ‘course run id’ is the identifier for a run of a course (ex. edX+DemoX+demo_run)

Parameters:

course_identifier (str) – The course id or course run id

Returns:

course id

Return type:

(str)

get_course_run(course_run_id)#

Return course_run data, including name, ID and seats.

Parameters:

course_run_id (string) – Course run ID (aka Course Key) in string format.

Returns:

Course run data provided by Course Catalog API.

Return type:

dict

get_course_run_identifiers(course_run_id)#

Return all course and course run keys and uuids for the specified course run id

get_program_by_uuid(program_uuid)#

Return single program by UUID, or None if not found.

Parameters:

program_uuid (string) – Program UUID in string form

Returns:

Program data provided by Course Catalog API

Return type:

dict

get_program_course_keys(program_uuid)#

Get a list of the course IDs (not course run IDs) contained in the program.

Parameters:

program_uuid (str) – Program UUID in string form

Returns:

List of course keys in string form that are included in the program

Return type:

list(str)

get_program_type_by_slug(slug)#

Get a program type by its slug.

Parameters:

slug (str) – The slug to identify the program type.

Returns:

A program type object.

Return type:

dict

traverse_pagination(response, api_url, content_filter_query, query_params)#

Traverse a paginated API response and extracts and concatenates “results” returned by API.

Parameters:
  • response (dict) – API response object.

  • api_url (str) – API endpoint path.

  • content_filter_query (dict) – query parameters used to filter catalog results.

  • query_params (dict) – query parameters used to paginate results.

Returns:

all the results returned by the API.

Return type:

list

class enterprise.api_client.discovery.CourseCatalogApiServiceClient(site=None)#

Bases: CourseCatalogApiClient

Catalog API client which uses the configured Catalog service user.

program_exists(program_uuid)#

Get whether the program exists or not.

class enterprise.api_client.discovery.NoAuthDiscoveryClient#

Bases: NoAuthAPIClient

Class to build a course discovery client to make calls to the discovery service.

API_BASE_URL = 'http://localhost:18381/'#
APPEND_SLASH = False#
enterprise.api_client.discovery.get_course_catalog_api_service_client(site=None)#

Returns an instance of the CourseCatalogApiServiceClient

Parameters:

site – (Site)

Returns:

(CourseCatalogServiceClient)

enterprise.api_client.ecommerce module#

Client for communicating with the E-Commerce API.

class enterprise.api_client.ecommerce.EcommerceApiClient(user)#

Bases: object

The API client to make calls to the E-Commerce API.

create_manual_enrollment_orders(enrollments)#

Calls ecommerce to create orders for the manual enrollments passed in.

enrollments should be a list of enrollments with the following format:

{
    "lms_user_id": <int>,
    "username": <str>,
    "email": <str>,
    "course_run_key": <str>
}

Since student.CourseEnrollment lives in LMS, we’re just passing around dicts of the relevant information.

get_course_final_price(mode, currency='$', enterprise_catalog_uuid=None)#

Get course mode’s SKU discounted price after applying any entitlement available for this user.

Returns:

Discounted price of the course mode.

Return type:

str

class enterprise.api_client.ecommerce.NoAuthEcommerceClient#

Bases: NoAuthAPIClient

The E-Commerce API client without authentication.

API_BASE_URL = 'http://localhost:18130'#
APPEND_SLASH = False#

enterprise.api_client.enterprise module#

Client for communicating with the Enterprise API.

class enterprise.api_client.enterprise.EnterpriseApiClient(user, expires_in=3600)#

Bases: UserAPIClient

The API client to make calls to the Enterprise API.

API_BASE_URL = 'http://localhost:8000/enterprise/api/v1/'#
APPEND_SLASH = True#
DEFAULT_VALUE_SAFEGUARD = <object object>#
ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT = 'enterprise_catalogs'#
ENTERPRISE_CUSTOMER_ENDPOINT = 'enterprise-customer'#
get_content_metadata(enterprise_customer, enterprise_catalogs=None)#

Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.

Parameters:
Returns:

List of dicts containing content metadata.

Return type:

list

enterprise.api_client.enterprise_catalog module#

Client for communicating with the Enterprise API.

class enterprise.api_client.enterprise_catalog.EnterpriseCatalogApiClient(user=None)#

Bases: UserAPIClient

The API client to make calls to the Enterprise Catalog API.

API_BASE_URL = 'http://localhost:18160/api/v1/'#
APPEND_SLASH = True#
CATALOG_DIFF_ENDPOINT = 'enterprise-catalogs/{}/generate_diff'#
CONTENT_METADATA_IDENTIFIER_ENDPOINT = 'enterprise-customer/{}/content-metadata/{}'#
ENTERPRISE_CATALOG_ENDPOINT = 'enterprise-catalogs'#
ENTERPRISE_CUSTOMER_ENDPOINT = 'enterprise-customer'#
GET_CONTENT_METADATA_ENDPOINT = 'enterprise-catalogs/{}/get_content_metadata'#
GET_CONTENT_METADATA_PAGE_SIZE = 50#
REFRESH_CATALOG_ENDPOINT = 'enterprise-catalogs/{}/refresh_metadata'#
contains_content_items(catalog_uuid, content_ids)#

Checks whether an enterprise catalog contains the given content.

The enterprise catalog endpoint does not differentiate between course_run_ids and program_uuids so they can be used interchangeably. The two query parameters are left in for backwards compatability with edx-enterprise.

create_enterprise_catalog(catalog_uuid, enterprise_id, enterprise_name, title, content_filter, enabled_course_modes, publish_audit_enrollment_urls, catalog_query_uuid, query_title=None, include_exec_ed_2u_courses=False)#

Creates an enterprise catalog.

delete_enterprise_catalog(catalog_uuid)#

Deletes an enterprise catalog.

enterprise_contains_content_items(enterprise_uuid, content_ids)#

Checks whether an enterprise customer has any catalogs that contain the provided content ids.

The endpoint does not differentiate between course_run_ids and program_uuids so they can be used interchangeably. The two query parameters are left in for backwards compatability with edx-enterprise.

get_catalog_content_count(catalog_uuid)#

Gets the content metadata count for a catalog from the first page of results

get_catalog_diff(enterprise_customer_catalog, content_keys, should_raise_exception=True)#

Gets the representational difference between a list of course keys and the current state of content under an enterprise catalog. This difference is returned as three buckets of data: items_not_found, items_not_included and items_found.

Parameters:
  • enterprise_customer_catalog (EnterpriseCustomerCatalog) – The catalog object whose content is being diffed.

  • content_keys (list) – List of string content keys

  • should_raise_exception (Bool) – Optional param for whether or not api response exceptions should be raised.

Returns:

dictionaries of content_keys to create items_to_delete (list): dictionaries of content_keys to delete items_found (list): dictionaries of content_keys and date_updated datetimes of content to update

Return type:

items_to_create (list)

get_content_metadata(enterprise_customer, enterprise_catalogs=None, content_keys_filter=None)#

Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.

Parameters:
  • enterprise_customer (EnterpriseCustomer) – The EnterpriseCustomer to return content metadata for.

  • enterprise_catalogs (EnterpriseCustomerCatalog) – Optional list of EnterpriseCustomerCatalog objects.

  • content_keys_filter (List) – List of content keys to filter by in the content metadata endpoint

Returns:

List of dicts containing content metadata.

Return type:

list

get_content_metadata_content_identifier(enterprise_uuid, content_id)#

Return all content metadata contained in the catalogs associated with the given EnterpriseCustomer and content_id.

static get_content_metadata_url(uuid)#

Get the url for the preview information for an enterprise catalog

get_enterprise_catalog(catalog_uuid, should_raise_exception=True)#

Gets an enterprise catalog.

Parameters:
  • catalog_uuid (uuid) – The uuid of an EnterpriseCatalog instance

  • should_raise_exception (bool) – Whether an exception should be logged if a catalog does not yet exist in enterprise-catalog. Defaults to True.

Returns:

a dictionary representing an enterprise catalog

Return type:

dict

refresh_catalogs(enterprise_catalogs)#

Kicks off async tasks to refresh catalogs so recent changes will populate to production without needing to wait for the daily jobs to run

Parameters:

enterprise_catalogs (EnterpriseCustomerCatalog) – List of EnterpriseCustomerCatalog objects to refresh

Returns:

Dict of async task ids for each catalog id

Return type:

Dict

traverse_get_content_metadata(api_url, query, catalog_uuid)#

Helper method to traverse over a paginated response from the enterprise-catalog service’s get_content_metadata endpoint.

update_enterprise_catalog(catalog_uuid, **kwargs)#

Updates an enterprise catalog.

class enterprise.api_client.enterprise_catalog.NoAuthEnterpriseCatalogClient#

Bases: NoAuthAPIClient

The enterprise catalog API client to make calls to the discovery service.

API_BASE_URL = 'http://localhost:18160'#
APPEND_SLASH = False#

enterprise.api_client.lms module#

Utilities to get details from the course catalog API.

class enterprise.api_client.lms.CertificatesApiClient(user, expires_in=3600)#

Bases: UserAPIClient

The API client to make calls to the LMS Certificates API.

Note that this API client requires a JWT token, and so it keeps its token alive.

API_BASE_URL = 'http://localhost:8000/api/certificates/v0/'#
APPEND_SLASH = True#
get_course_certificate(course_id, username)#

Retrieve the certificate for the given username for the given course_id.

Args: * course_id (str): The string value of the course’s unique identifier * username (str): The username ID identifying the user for which to retrieve the certificate

Returns:

a dict containing:

  • username: A string representation of an user’s username passed in the request.

  • course_id: A string representation of a Course ID.

  • certificate_type: A string representation of the certificate type.

  • created_date: Datetime the certificate was created (tz-aware).

  • status: A string representation of the certificate status.

  • is_passing: True if the certificate has a passing status, False if not.

  • download_url: A string representation of the certificate url.

  • grade: A string representation of a float for the user’s course grade.

class enterprise.api_client.lms.CourseApiClient#

Bases: NoAuthAPIClient

The API client to make calls to the Course API.

API_BASE_URL = 'http://localhost:8000/api/courses/v1/'#
APPEND_SLASH = True#
get_course_details(course_id)#

Retrieve all available details about a course.

Parameters:

course_id (str) – The course ID identifying the course for which to retrieve details.

Returns:

Contains keys identifying those course details available from the courses API (e.g., name).

Return type:

dict

class enterprise.api_client.lms.EmbargoApiClient#

Bases: object

Client interface for using the edx-platform embargo API.

static redirect_if_blocked(request, course_run_ids, user=None)#

Return redirect to embargo error page if the given user is blocked.

class enterprise.api_client.lms.EnrollmentApiClient#

Bases: BackendServiceAPIClient

The API client to make calls to the Enrollment API.

API_BASE_URL = 'http://localhost:8000/api/enrollment/v1/'#
enroll_user_in_course(username, course_id, mode, cohort=None, enterprise_uuid=None)#

Call the enrollment API to enroll the user in the course specified by course_id.

Parameters:
  • username (str) – The username by which the user goes on the OpenEdX platform

  • course_id (str) – The string value of the course’s unique identifier

  • mode (str) – The enrollment mode which should be used for the enrollment

  • cohort (str) – Add the user to this named cohort

  • enterprise_uuid (str) – Add course enterprise uuid

Returns:

A dictionary containing details of the enrollment, including course details, mode, username, etc.

Return type:

dict

get_course_details(course_id)#

Query the Enrollment API for the course details of the given course_id.

Parameters:

course_id (str) – The string value of the course’s unique identifier

Returns:

A dictionary containing details about the course, in an enrollment context (allowed modes, etc.)

Return type:

dict

get_course_enrollment(username, course_id)#

Query the enrollment API to get information about a single course enrollment.

Parameters:
  • username (str) – The username by which the user goes on the OpenEdX platform

  • course_id (str) – The string value of the course’s unique identifier

Returns:

A dictionary containing details of the enrollment, including course details, mode, username, etc.

Return type:

dict

get_course_modes(course_id)#

Query the Enrollment API for the specific course modes that are available for the given course_id.

Parameters:

course_id (str) – The string value of the course’s unique identifier

Returns:

A list of course mode dictionaries.

Return type:

list

get_enrolled_courses(username)#

Query the enrollment API to get a list of the courses a user is enrolled in.

Parameters:

username (str) – The username by which the user goes on the OpenEdX platform

Returns:

A list of course objects, along with relevant user-specific enrollment details.

Return type:

list

has_course_mode(course_run_id, mode)#

Query the Enrollment API to see whether a course run has a given course mode available.

Parameters:

course_run_id (str) – The string value of the course run’s unique identifier

Returns:

Whether the course run has the given mode avaialble for enrollment.

Return type:

bool

is_enrolled(username, course_run_id)#

Query the enrollment API and determine if a learner is enrolled in a course run.

Parameters:
  • username (str) – The username by which the user goes on the OpenEdX platform

  • course_run_id (str) – The string value of the course’s unique identifier

Returns:

Indicating whether the user is enrolled in the course run. Returns False under any errors.

Return type:

bool

unenroll_user_from_course(username, course_id)#

Call the enrollment API to unenroll the user in the course specified by course_id. :param username: The username by which the user goes on the OpenEdx platform :type username: str :param course_id: The string value of the course’s unique identifier :type course_id: str

Returns:

Whether the unenrollment succeeded

Return type:

bool

update_course_enrollment_mode_for_user(username, course_id, mode)#

Call the enrollment API to update a user’s course enrollment to the specified mode, e.g. “audit”.

Parameters:
  • username (str) – The username by which the user goes on the OpenEdx platform

  • course_id (str) – The string value of the course’s unique identifier

  • mode (str) – The string value of the course mode, e.g. “audit”

Returns:

A dictionary containing details of the enrollment, including course details, mode, username, etc.

Return type:

dict

class enterprise.api_client.lms.GradesApiClient(user, expires_in=3600)#

Bases: UserAPIClient

The API client to make calls to the LMS Grades API.

Note that this API client requires a JWT token, and so it keeps its token alive.

API_BASE_URL = 'http://localhost:8000/api/grades/v1/'#
APPEND_SLASH = True#
MAX_RETRIES = 4#
get_course_assessment_grades(course_id, username)#

Retrieve the assessment grades for the given username for the given course_id.

Args: * course_id (str): The string value of the course’s unique identifier * username (str): The username ID identifying the user for which to retrieve the grade.

Raises:

HTTPError if no grade found for the given user+course.

Returns:

a list of dicts containing:

  • attempted: A boolean representing whether the learner has attempted the subsection yet.

  • subsection_name: String representation of the subsection’s name.

  • category: String representation of the subsection’s category.

  • label: String representation of the subsection’s label.

  • score_possible: The total amount of points that the learner could have earned on the subsection.

  • score_earned: The total amount of points that the learner earned on the subsection.

  • percent: A float representing the overall grade for the course.

  • module_id: The ID of the subsection.

get_course_grade(course_id, username)#

Retrieve the grade for the given username for the given course_id.

Args: * course_id (str): The string value of the course’s unique identifier * username (str): The username ID identifying the user for which to retrieve the grade.

Raises:

HTTPError if no grade found for the given user+course.

Returns:

a dict containing:

  • username: A string representation of a user’s username passed in the request.

  • course_key: A string representation of a Course ID.

  • passed: Boolean representing whether the course has been passed according the course’s grading policy.

  • percent: A float representing the overall grade for the course

  • letter_grade: A letter grade as defined in grading_policy (e.g. ‘A’ ‘B’ ‘C’ for 6.002x) or None

class enterprise.api_client.lms.NoAuthLMSClient#

Bases: NoAuthAPIClient

The LMS API client to make calls to the LMS without authentication.

API_BASE_URL = 'http://localhost:8000'#
APPEND_SLASH = False#
get_health()#

Retrieve health details for LMS service.

Returns:

Response containing LMS service health.

Return type:

dict

class enterprise.api_client.lms.ThirdPartyAuthApiClient(user, expires_in=3600)#

Bases: UserAPIClient

The API client to make calls to the Third Party Auth API.

API_BASE_URL = 'http://localhost:8000/api/third_party_auth/v0/'#
get_remote_id(identity_provider, username)#

Retrieve the remote identifier for the given username.

Args: * identity_provider (str): identifier slug for the third-party authentication service used during SSO. * username (str): The username ID identifying the user for which to retrieve the remote name.

Returns:

the remote name of the given user. None if not found.

Return type:

string or None

get_username_from_remote_id(identity_provider, remote_id)#

Retrieve the remote identifier for the given username.

Args: * identity_provider (str): identifier slug for the third-party authentication service used during SSO. * remote_id (str): The remote id identifying the user for which to retrieve the usernamename.

Returns:

the username of the given user. None if not found.

Return type:

string or None

enterprise.api_client.open_ai module#

OpenAI client

enterprise.api_client.open_ai.chat_completion(prompt, role, model='gpt-3.5-turbo')#

Use chatGPT https://api.openai.com/v1/chat/completions endpoint to generate a response.

Parameters:
  • prompt (str) – ChatGPT prompt

  • role (str) – ChatGPT role to assume for the prompt.

  • model (str) – ChatGPT model to use for the prompt completion.

Returns:

Prompt response from OpenAI.

Return type:

(str)

enterprise.api_client.sso_orchestrator module#

Api client for the SSO Orchestrator API.

class enterprise.api_client.sso_orchestrator.EnterpriseSSOOrchestratorApiClient#

Bases: object

The enterprise API client to communicate with the SSO Orchestrator API. Reads conf settings values to determine orchestration paths and credentials.

Required settings values: - LMS_ROOT_URL - SSO_ORCHESTRATOR_API_BASE_URL - SSO_ORCHESTRATOR_CONFIGURE_PATH - SSO_ORCHESTRATOR_BASIC_AUTH_USERNAME - SSO_ORCHESTRATOR_BASIC_AUTH_PASSWORD

configure_edx_oauth(enterprise_customer)#

Configure SSO to GetSmarter using edX credentials via Auth0.

Parameters:

enterprise_customer (EnterpriseCustomer) – The enterprise customer for which to configure edX OAuth.

Returns:

Auth0 Organization ID.

Return type:

str

Raises:

SsoOrchestratorClientError – If the request to the SSO Orchestrator API failed.

configure_sso_orchestration_record(config_data, config_pk, enterprise_data, is_sap=False, updating_existing_record=False, sap_config_data=None)#

configure an SSO orchestration record

exception enterprise.api_client.sso_orchestrator.SsoOrchestratorClientError(*args, **kwargs)#

Bases: RequestException

Indicate a problem when interacting with an enterprise api client.

Module contents#