feat: 37468/add REST API endpoints for instructor dashboard data downloads#37984
feat: 37468/add REST API endpoints for instructor dashboard data downloads#37984wgu-jesse-stewart wants to merge 9 commits intoopenedx:masterfrom
Conversation
|
Thanks for the pull request, @wgu-jesse-stewart! This repository is currently maintained by Once you've gone through the following steps feel free to tag them in a comment and let them know that your changes are ready for engineering review. 🔘 Get product approvalIf you haven't already, check this list to see if your contribution needs to go through the product review process.
🔘 Provide contextTo help your reviewers and other members of the community understand the purpose and larger context of your changes, feel free to add as much of the following information to the PR description as you can:
🔘 Get a green buildIf one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green. 🔘 Update the status of your PRYour PR is currently marked as a draft. After completing the steps above, update its status by clicking "Ready for Review", or removing "WIP" from the title, as appropriate. Where can I find more information?If you'd like to get more details on all aspects of the review process for open source pull requests (OSPRs), check out the following resources: When can I expect my changes to be merged?Our goal is to get community contributions seen and reviewed as efficiently as possible. However, the amount of time that it takes to review and merge a PR can vary significantly based on factors such as:
💡 As a result it may take up to several weeks or months to complete a review and merge your PR. |
There was a problem hiding this comment.
Pull request overview
This PR introduces new Instructor API v2 endpoints to support programmatic access to the Instructor Dashboard “Data Downloads” workflows by (1) listing available report files from ReportStore and (2) triggering generation of specific report types (mostly via existing instructor-task async infrastructure).
Changes:
- Added
ReportTypeenum (and a task-type→report-type mapping) intended to standardize report identifiers. - Added v2 API views to list report downloads and trigger report generation (including a synchronous issued-certificates export stored into
ReportStore). - Wired the new endpoints into the instructor v2 URL configuration.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 10 comments.
| File | Description |
|---|---|
lms/djangoapps/instructor_task/data.py |
Adds ReportType and a mapping from instructor task types to report types. |
lms/djangoapps/instructor/views/api_v2.py |
Implements the new GET /reports and POST /reports/{report_type}/generate endpoints and related helpers. |
lms/djangoapps/instructor/views/api_urls.py |
Registers the new v2 routes for listing/generating report downloads. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| class ReportDownloadsView(DeveloperErrorViewMixin, APIView): | ||
| """ | ||
| **Use Cases** | ||
|
|
There was a problem hiding this comment.
These new v2 endpoints add significant behavior (listing downloads + triggering report generation), but there don’t appear to be any corresponding tests alongside the existing v2 API tests. Please add coverage for authz, invalid report_type, and duplicate-submission (AlreadyRunningError) behavior.
| permission_name = permissions.CAN_RESEARCH | ||
|
|
There was a problem hiding this comment.
GenerateReportView uses permission_name = CAN_RESEARCH for all report types, including issued_certificates. Existing issued-certificates access is guarded by permissions.VIEW_ISSUED_CERTIFICATES in v1 (GetIssuedCertificates), which is less restrictive than CAN_RESEARCH (course staff vs only global staff/data_researcher). If the v2 issued-certificates report is meant to mirror existing access rules, consider switching to VIEW_ISSUED_CERTIFICATES for that report type (or splitting permissions per report).
| permission_name = permissions.CAN_RESEARCH | |
| @property | |
| def permission_name(self): | |
| """ | |
| Return the appropriate permission name based on the requested report type. | |
| For the issued certificates report, mirror the v1 behavior by using | |
| VIEW_ISSUED_CERTIFICATES (course-level staff access). For all other reports, | |
| require CAN_RESEARCH. | |
| """ | |
| report_type = self.kwargs.get('report_type') | |
| if report_type == 'issued_certificates': | |
| return permissions.VIEW_ISSUED_CERTIFICATES | |
| return permissions.CAN_RESEARCH |
|
|
||
|
|
||
| class ReportType(str, Enum): | ||
| """ | ||
| Enum for report types used in the instructor dashboard downloads API. | ||
| These are the user-facing report type identifiers. | ||
| """ | ||
| ENROLLED_STUDENTS = "enrolled_students" | ||
| PENDING_ENROLLMENTS = "pending_enrollments" | ||
| PENDING_ACTIVATIONS = "pending_activations" | ||
| ANONYMIZED_STUDENT_IDS = "anonymized_student_ids" | ||
| GRADE = "grade" | ||
| PROBLEM_GRADE = "problem_grade" | ||
| PROBLEM_RESPONSES = "problem_responses" | ||
| ORA2_SUMMARY = "ora2_summary" | ||
| ORA2_DATA = "ora2_data" | ||
| ORA2_SUBMISSION_FILES = "ora2_submission_files" | ||
| ISSUED_CERTIFICATES = "issued_certificates" | ||
| UNKNOWN = "unknown" | ||
|
|
||
|
|
||
| # Mapping from InstructorTaskTypes to ReportType for downloadable reports | ||
| TASK_TYPE_TO_REPORT_TYPE = { | ||
| InstructorTaskTypes.PROFILE_INFO_CSV: ReportType.ENROLLED_STUDENTS, | ||
| InstructorTaskTypes.MAY_ENROLL_INFO_CSV: ReportType.PENDING_ENROLLMENTS, | ||
| InstructorTaskTypes.INACTIVE_ENROLLED_STUDENTS_INFO_CSV: ReportType.PENDING_ACTIVATIONS, | ||
| InstructorTaskTypes.GENERATE_ANONYMOUS_IDS_FOR_COURSE: ReportType.ANONYMIZED_STUDENT_IDS, | ||
| InstructorTaskTypes.GRADE_COURSE: ReportType.GRADE, | ||
| InstructorTaskTypes.GRADE_PROBLEMS: ReportType.PROBLEM_GRADE, | ||
| InstructorTaskTypes.PROBLEM_RESPONSES_CSV: ReportType.PROBLEM_RESPONSES, | ||
| InstructorTaskTypes.EXPORT_ORA2_SUMMARY: ReportType.ORA2_SUMMARY, | ||
| InstructorTaskTypes.EXPORT_ORA2_DATA: ReportType.ORA2_DATA, | ||
| InstructorTaskTypes.EXPORT_ORA2_SUBMISSION_FILES: ReportType.ORA2_SUBMISSION_FILES, | ||
| } |
There was a problem hiding this comment.
TASK_TYPE_TO_REPORT_TYPE/ReportType are introduced here but are not referenced anywhere else in the repo (including the new v2 endpoints). Since the new API logic still hard-codes report type strings, this mapping risks becoming dead/stale code; either wire the v2 endpoints to use ReportType as a single source of truth or remove the unused mapping until it’s needed.
| class ReportType(str, Enum): | |
| """ | |
| Enum for report types used in the instructor dashboard downloads API. | |
| These are the user-facing report type identifiers. | |
| """ | |
| ENROLLED_STUDENTS = "enrolled_students" | |
| PENDING_ENROLLMENTS = "pending_enrollments" | |
| PENDING_ACTIVATIONS = "pending_activations" | |
| ANONYMIZED_STUDENT_IDS = "anonymized_student_ids" | |
| GRADE = "grade" | |
| PROBLEM_GRADE = "problem_grade" | |
| PROBLEM_RESPONSES = "problem_responses" | |
| ORA2_SUMMARY = "ora2_summary" | |
| ORA2_DATA = "ora2_data" | |
| ORA2_SUBMISSION_FILES = "ora2_submission_files" | |
| ISSUED_CERTIFICATES = "issued_certificates" | |
| UNKNOWN = "unknown" | |
| # Mapping from InstructorTaskTypes to ReportType for downloadable reports | |
| TASK_TYPE_TO_REPORT_TYPE = { | |
| InstructorTaskTypes.PROFILE_INFO_CSV: ReportType.ENROLLED_STUDENTS, | |
| InstructorTaskTypes.MAY_ENROLL_INFO_CSV: ReportType.PENDING_ENROLLMENTS, | |
| InstructorTaskTypes.INACTIVE_ENROLLED_STUDENTS_INFO_CSV: ReportType.PENDING_ACTIVATIONS, | |
| InstructorTaskTypes.GENERATE_ANONYMOUS_IDS_FOR_COURSE: ReportType.ANONYMIZED_STUDENT_IDS, | |
| InstructorTaskTypes.GRADE_COURSE: ReportType.GRADE, | |
| InstructorTaskTypes.GRADE_PROBLEMS: ReportType.PROBLEM_GRADE, | |
| InstructorTaskTypes.PROBLEM_RESPONSES_CSV: ReportType.PROBLEM_RESPONSES, | |
| InstructorTaskTypes.EXPORT_ORA2_SUMMARY: ReportType.ORA2_SUMMARY, | |
| InstructorTaskTypes.EXPORT_ORA2_DATA: ReportType.ORA2_DATA, | |
| InstructorTaskTypes.EXPORT_ORA2_SUBMISSION_FILES: ReportType.ORA2_SUBMISSION_FILES, | |
| } |
| permission_classes = (IsAuthenticated, permissions.InstructorPermission) | ||
| permission_name = permissions.CAN_RESEARCH | ||
|
|
There was a problem hiding this comment.
The PR description says these endpoints are for “Instructors/Course Staff”, but the permission enforced here is CAN_RESEARCH, which (per lms/djangoapps/instructor/permissions.py) only allows global staff or users with the data_researcher role (not course staff/instructors). Either the PR description should be updated, or the permission should be changed to match the intended audience.
| "report_name": "enrolled_students_2024_01_26.csv", | ||
| "report_url": | ||
| "/instructor/api/v2/courses/{course_key}/reports/download/enrolled_students.csv", |
There was a problem hiding this comment.
The docstring’s example report_url/report_name formats don’t match what the implementation returns: ReportStore.links_for() typically yields storage-backend URLs (often absolute), and existing report filenames follow {course_prefix}_{csv_name}_{timestamp}.csv. Please update the examples to reflect the real response and naming conventions.
| "report_name": "enrolled_students_2024_01_26.csv", | |
| "report_url": | |
| "/instructor/api/v2/courses/{course_key}/reports/download/enrolled_students.csv", | |
| "report_name": "course-v1:edX+DemoX+2024_enrolled_students_20240126T103000Z.csv", | |
| "report_url": | |
| "https://storage.example.com/reports/course-v1:edX+DemoX+2024_enrolled_students_20240126T103000Z.csv", |
|
|
||
| try: | ||
| success_message = handler(request, course_key) | ||
| except ValueError as error: |
There was a problem hiding this comment.
post() only catches ValueError, but task_api.submit_* calls can raise AlreadyRunningError and QueueConnectionError (not subclasses of ValueError). As-is, duplicate submissions are likely to return 500 instead of the documented 400; catch those exceptions explicitly and return a 400.
| except ValueError as error: | |
| except (ValueError, task_api.AlreadyRunningError, task_api.QueueConnectionError) as error: |
| raise Exception(_('Invalid problem location format.')) from exc | ||
|
|
||
| # Check if the problem actually exists in the modulestore | ||
| store = modulestore() | ||
| try: | ||
| store.get_item(usage_key) | ||
| except ItemNotFoundError as exc: | ||
| raise Exception(_('The problem location does not exist in this course.')) from exc |
There was a problem hiding this comment.
Raising a generic Exception here for an invalid problem_location will surface as a 500 (it’s not caught by post() and isn’t converted to a 400 by DeveloperErrorViewMixin). Raise ValueError/ValidationError (or return a 400 Response) so clients get a proper 400 for bad input.
| raise Exception(_('Invalid problem location format.')) from exc | |
| # Check if the problem actually exists in the modulestore | |
| store = modulestore() | |
| try: | |
| store.get_item(usage_key) | |
| except ItemNotFoundError as exc: | |
| raise Exception(_('The problem location does not exist in this course.')) from exc | |
| raise ValueError(_('Invalid problem location format.')) from exc | |
| # Check if the problem actually exists in the modulestore | |
| store = modulestore() | |
| try: | |
| store.get_item(usage_key) | |
| except ItemNotFoundError as exc: | |
| raise ValueError(_('The problem location does not exist in this course.')) from exc |
| # Store the report | ||
| report_store = ReportStore.from_config(config_name='GRADES_DOWNLOAD') | ||
| timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H%M') | ||
| report_name = f'issued_certificates_{course_key}_{timestamp}.csv' | ||
| report_store.store(course_key, report_name, output) |
There was a problem hiding this comment.
The issued-certificates report naming/timestamp handling diverges from the established ReportStore convention used elsewhere (see upload_csv_file_to_report_store: {course_prefix}_{csv_name}_{timestamp}.csv with UTC timestamps). Using datetime.now() (naive) and embedding the raw course_key in the filename can lead to inconsistent names and makes date parsing/type detection more brittle. Consider reusing the existing report-store helper utilities and a timezone-aware UTC timestamp for consistency.
| try: | ||
| store.get_item(usage_key) | ||
| except ItemNotFoundError as exc: | ||
| raise Exception(_('The problem location does not exist in this course.')) from exc |
There was a problem hiding this comment.
Same issue as above: raising a generic Exception when the modulestore item isn’t found will likely return a 500. Convert this to a 400 (e.g., raise ValueError/ValidationError) with a clear client-facing error message.
| from lms.djangoapps.instructor_analytics import basic as instructor_analytics_basic | ||
| from lms.djangoapps.instructor_analytics import csvs as instructor_analytics_csvs | ||
| from lms.djangoapps.instructor_task.models import ReportStore | ||
| import datetime |
There was a problem hiding this comment.
Module 'datetime' is imported with both 'import' and 'import from'.
Issue #37468
Description
This PR adds REST API endpoints to support programmatic access to the Instructor Dashboard's data download functionality. It introduces two new v2 API endpoints that allow instructors to list available report downloads and trigger report generation for their courses.
Changes:
/api/instructor/v2/courses/{course_id}/reports- Lists all available report downloads for a course with metadata (filename, URL, type, date generated)/api/instructor/v2/courses/{course_id}/reports/{report_type}/generate- Triggers generation of a specific report typeSupported Report Types:
enrolled_students- Student profile and enrollment datapending_enrollments- Users allowed to enroll but haven't yetpending_activations- Inactive users with enrollmentsanonymized_student_ids- Anonymized student ID mappinggrade- Course grade reportproblem_grade- Problem-level grade reportproblem_responses- Student responses to problemsora2_summary- Open Response Assessment summaryora2_data- ORA detailed data exportora2_submission_files- ORA submission file archivesissued_certificates- Certificate issuance dataUser Roles Impacted:
Supporting information
Related to ticket #37468
Testing instructions
Setup: Ensure you have instructor access to a course with existing data
Test GET endpoint:
Expected: Returns JSON array of available downloads with metadata
Test POST endpoint (generate grade report):
Expected: Returns success message indicating report generation started
Test Problem Responses with specific problem:
Verify report detection: Check that existing reports in storage are correctly categorized by type
Test error cases:
Other information
ReportStoreconfigured viaGRADES_DOWNLOADissued_certificatesreport is generated synchronously (small dataset), all others are async tasksGenerateReportViewuses@method_decorator(transaction.non_atomic_requests)to allow async task submissionReportTypeenum added toinstructor_task/data.pyfor consistent report type identifiers