feat: add migration section

This commit is contained in:
swve
2026-04-25 12:44:06 +02:00
parent f3491a1b37
commit 7f657c42d7
9 changed files with 4137 additions and 288 deletions

View File

@@ -190,6 +190,7 @@ const iconMap = {
'/developers/architecture': TreeStructure,
'/developers/contributing': GitBranch,
'/developers/api': Plug,
'/developers/migration': ArrowsClockwise,
// Developers > Architecture
'/developers/architecture/frontend': Browser,
@@ -203,6 +204,11 @@ const iconMap = {
// Developers > API
'/developers/api/authentication': Key,
'/developers/api/endpoints': Plug,
// Developers > Migration
'/developers/migration/programmatic': Code,
'/developers/migration/activity-types': Stack,
'/developers/migration/assisted': Brain,
}
function getIcon(route) {

View File

@@ -13,13 +13,22 @@ function Breadcrumb() {
if (!activePath || activePath.length <= 1) return null
// Nextra emits both a folder entry and its index page with the same route
// (e.g. /developers/migration appears twice once you open /developers/migration).
// Collapse consecutive duplicates so React keys stay unique and the trail
// does not show the same crumb twice.
const trail = activePath.filter((item, i, arr) => {
const next = arr[i + 1]
return !next || next.route !== item.route
})
return (
<nav className="lh-breadcrumb" aria-label="breadcrumb">
{activePath.map((item, i) => {
const isLast = i === activePath.length - 1
{trail.map((item, i) => {
const isLast = i === trail.length - 1
const title = typeof item.title === 'string' ? item.title : item.name
return (
<span key={item.route || i} className="lh-breadcrumb-item">
<span key={`${item.route || ''}-${i}`} className="lh-breadcrumb-item">
{i > 0 && <span className="lh-breadcrumb-sep">/</span>}
{isLast ? (
<span className="lh-breadcrumb-current">{title}</span>
@@ -66,12 +75,13 @@ function Pagination() {
)
}
function EditOnGitHub() {
const pathname = usePathname()
function EditOnGitHub({ filePath }) {
// `filePath` comes from Nextra page metadata and is the actual source path
// relative to the docs repo root (e.g. "content/cli/index.mdx"). Using it
// directly avoids guessing folder-index vs leaf-file from the URL.
if (!filePath) return null
let filePath = pathname === '/' ? '/index' : pathname
const gitHubBase = 'https://github.com/learnhouse/docs/edit/main/content'
const href = `${gitHubBase}${filePath}.mdx`
const href = `https://github.com/learnhouse/docs/edit/main/${filePath}`
return (
<a
@@ -165,7 +175,7 @@ export default function Wrapper({ children, toc, metadata }) {
<article className="lh-article">
<div className="lh-article-header">
<Breadcrumb />
{!isHome && <EditOnGitHub />}
{!isHome && <EditOnGitHub filePath={metadata?.filePath} />}
</div>
<div className="lh-prose">
{children}

View File

@@ -2,5 +2,6 @@
"index": "Overview",
"architecture": "Architecture",
"contributing": "Contributing",
"api": "API Reference"
"api": "API Reference",
"migration": "Migration"
}

View File

@@ -0,0 +1,6 @@
{
"index": "Overview",
"programmatic": "Programmatic Migration",
"activity-types": "Activity Types Reference",
"assisted": "AI-Assisted Migration"
}

View File

@@ -0,0 +1,490 @@
import { Callout } from 'nextra/components'
# Activity Types Reference
Every activity in LearnHouse is described by two enums and one JSON `content` blob:
- `activity_type` -- one of `TYPE_DYNAMIC`, `TYPE_VIDEO`, `TYPE_DOCUMENT`, `TYPE_ASSIGNMENT`, `TYPE_CUSTOM`, `TYPE_SCORM`.
- `activity_sub_type` -- a more specific variant within the type (e.g. `SUBTYPE_VIDEO_YOUTUBE` vs `SUBTYPE_VIDEO_HOSTED`).
- `content` -- a JSON object whose shape depends on the sub-type.
This page is the canonical reference for what `content` (and `details`) must contain for each combination, alongside the create endpoint to use.
<Callout type="info">
The list of valid types and sub-types is enforced by the API as Python enums. Sending an unknown value returns a 422 Unprocessable Entity. The full enum is reproduced at the bottom of this page.
</Callout>
## Dynamic activities
`activity_type: "TYPE_DYNAMIC"` -- pages rendered inside the activity viewer.
### Dynamic Page (`SUBTYPE_DYNAMIC_PAGE`)
The flagship activity type. `content` is a [TipTap](https://tiptap.dev/) / ProseMirror document.
**Create endpoint:** `POST /api/v1/activities/` (JSON body, see [Programmatic Migration](/developers/migration/programmatic#3a-generic-json-create----post-apiv1activities)).
**Initial content:** start empty (`"content": {}`) and update later, or send a complete document on creation:
```json
{
"name": "Welcome to the course",
"chapter_id": 7,
"activity_type": "TYPE_DYNAMIC",
"activity_sub_type": "SUBTYPE_DYNAMIC_PAGE",
"content": {
"type": "doc",
"content": [
{
"type": "heading",
"attrs": { "level": 1 },
"content": [{ "type": "text", "text": "Welcome" }]
},
{
"type": "paragraph",
"content": [
{ "type": "text", "text": "This is a " },
{ "type": "text", "text": "bold", "marks": [{ "type": "bold" }] },
{ "type": "text", "text": " introduction." }
]
},
{
"type": "bulletList",
"content": [
{
"type": "listItem",
"content": [{
"type": "paragraph",
"content": [{ "type": "text", "text": "Learning objective 1" }]
}]
},
{
"type": "listItem",
"content": [{
"type": "paragraph",
"content": [{ "type": "text", "text": "Learning objective 2" }]
}]
}
]
}
]
}
}
```
The root must be `{ "type": "doc", "content": [...] }`. Each child is a block node.
#### Valid TipTap block types
The API validates dynamic-page content against this whitelist (unknown types are accepted but logged):
```
paragraph, heading, bulletList, orderedList, listItem,
codeBlock, table, tableRow, tableHeader, tableCell,
horizontalRule, hardBreak, text,
calloutInfo, calloutWarning,
blockImage, blockVideo, blockPDF, blockAudio, blockMathEquation,
blockEmbed, blockQuiz, blockUser, blockWebPreview,
flipcard, scenarios, button, badge
```
The `block*` types correspond to LearnHouse's custom node extensions. Standard TipTap block types (`paragraph`, `heading`, etc.) behave as in any TipTap editor.
#### Inline marks
Text nodes (`"type": "text"`) can carry inline marks:
```json
{ "type": "text", "text": "see link", "marks": [
{ "type": "link", "attrs": { "href": "https://example.com" } }
] }
```
Supported marks: `bold`, `italic`, `code`, `link`, plus the standard StarterKit marks.
<Callout type="info">
The web client tolerates `strong` and `em` (HTML aliases) and rewrites them to `bold` / `italic` on render. Prefer `bold` / `italic` directly in API payloads.
</Callout>
#### Alternative: simplified blocks-only content
When the [AI-assisted migration](/developers/migration/assisted) creates a dynamic-page activity from a single image or audio file, it writes a simpler legacy shape instead of TipTap JSON:
```json
{
"blocks": [
{
"block_uuid": "block_7522d174-...",
"block_type": "BLOCK_IMAGE",
"content": { "file_id": "3a80fc43-...", "file_format": "png" }
}
]
}
```
The dynamic-page renderer accepts both shapes. Use the TipTap shape when authoring rich content; the simpler `blocks` shape exists primarily for migration-style media-only pages.
#### Embedding media blocks
Media blocks (`blockImage`, `blockVideo`, `blockPDF`, `blockAudio`) are atom nodes that point to a previously-uploaded Block via the `blockObject` attribute:
```json
{
"type": "blockImage",
"attrs": {
"blockObject": {
"block_uuid": "block_2a8...",
"block_type": "BLOCK_IMAGE",
"content": {
"file_id": "block_a1b2c3...",
"file_format": "png",
"file_name": "diagram.png",
"file_size": 24576,
"file_type": "image/png",
"activity_uuid": "activity_91c..."
}
},
"size": { "width": 600 },
"alignment": "center"
}
}
```
The full `BlockRead` object returned by `POST /api/v1/blocks/image` (or `/video` / `/pdf` / `/audio`) goes into `attrs.blockObject`. Attribute defaults per block:
| Block node | Required attrs | Optional attrs |
| --- | --- | --- |
| `blockImage` | `blockObject` | `size: { width }`, `alignment` (`center`, `left`, `right`), `unsplash_*` |
| `blockVideo` | `blockObject` | -- |
| `blockPDF` | `blockObject` | -- |
| `blockAudio` | `blockObject` | -- |
#### Code blocks
Code blocks include a `language` attribute consumed by lowlight syntax highlighting:
```json
{
"type": "codeBlock",
"attrs": { "language": "python" },
"content": [
{ "type": "text", "text": "def hello():\n print(\"Hello, world!\")" }
]
}
```
Common languages: `python`, `javascript`, `typescript`, `java`, `cpp`, `c`, `rust`, `go`, `php`, `ruby`, `kotlin`, `csharp`, `swift`, `scala`, `perl`, `r`, plus anything supported by `lowlight`'s `common` set.
#### Quiz blocks
```json
{
"type": "blockQuiz",
"attrs": {
"quizId": "quiz_1",
"questions": [
{
"id": "q1",
"question": "What does Python's print() do?",
"options": [
{ "id": "a", "text": "Outputs to stdout", "correct": true },
{ "id": "b", "text": "Reads input", "correct": false }
]
}
]
}
}
```
The exact `questions` schema is the same one rendered by the editor's `QuizBlockComponent`. Inspect a real quiz in the editor and export the JSON if you need an authoritative shape -- it has evolved over time and is best treated as opaque to migration scripts.
### Dynamic Markdown (`SUBTYPE_DYNAMIC_MARKDOWN`)
Renders a Markdown file fetched from a remote URL.
```json
{
"name": "README",
"chapter_id": 7,
"activity_type": "TYPE_DYNAMIC",
"activity_sub_type": "SUBTYPE_DYNAMIC_MARKDOWN",
"content": { "markdown_url": "https://github.com/user/repo/raw/main/README.md" }
}
```
The viewer fetches and renders the URL on each page load.
### Dynamic Embed (`SUBTYPE_DYNAMIC_EMBED`)
Renders an arbitrary URL inside an iframe (Google Docs, Notion, Figma, etc.):
```json
{
"name": "Course brief",
"chapter_id": 7,
"activity_type": "TYPE_DYNAMIC",
"activity_sub_type": "SUBTYPE_DYNAMIC_EMBED",
"content": { "embed_url": "https://docs.google.com/document/d/abc123/edit" }
}
```
The embedded site must allow iframe embedding (`X-Frame-Options` / `Content-Security-Policy`). LearnHouse cannot work around a destination's frame-blocking headers.
## Video activities
`activity_type: "TYPE_VIDEO"`.
### Hosted video (`SUBTYPE_VIDEO_HOSTED`)
Created via the dedicated multipart endpoint -- you cannot create a hosted video by sending JSON to `/activities/`.
<Callout type="info">
The endpoint creates the activity with `published: false` regardless of any payload field. To publish, follow up with `PUT /api/v1/activities/{activity_uuid}` setting `{"published": true}`. The same is true for `/activities/external_video` and `/activities/documentpdf`.
</Callout>
**Create endpoint:** `POST /api/v1/activities/video`
```bash
curl -X POST "http://localhost:1338/api/v1/activities/video" \
-H "Authorization: Bearer lh_your_api_token" \
-F 'name=Lesson 1 walkthrough' \
-F 'chapter_id=7' \
-F 'video_file=@./lesson-01.mp4;type=video/mp4' \
-F 'details={"startTime":0,"endTime":null,"autoplay":false,"muted":false}'
```
`Content-Type` is checked strictly -- only `video/mp4` and `video/webm` are accepted. The server stores the file, builds the `content` object internally, and returns the resulting `ActivityRead`. The persisted `content` looks like:
```json
{
"filename": "1e231d81-ae8a-4142-b165-e2b158057bc1_video.mp4",
"activity_uuid": "activity_ec39ecc1-..."
}
```
`filename` is the safe-on-disk name LearnHouse generated; the player resolves it through `/api/v1/content/...`. The `details` form field is a JSON-encoded string with player options:
| `details` key | Type | Notes |
| --- | --- | --- |
| `startTime` | number (seconds) | Seek-to point on play |
| `endTime` | number or `null` | Stop point (omit to play to end) |
| `autoplay` | boolean | -- |
| `muted` | boolean | -- |
### External video (`SUBTYPE_VIDEO_YOUTUBE`)
For YouTube and Vimeo embeds. Note the sub-type name is historical -- the same sub-type covers Vimeo too, distinguished by the `type` field in the request.
**Create endpoint:** `POST /api/v1/activities/external_video`
```bash
curl -X POST "http://localhost:1338/api/v1/activities/external_video" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"name": "Intro lecture",
"uri": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"type": "youtube",
"chapter_id": "7",
"details": "{\"startTime\":0,\"endTime\":null,\"autoplay\":false,\"muted\":false}"
}'
```
| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `name` | string | Yes | Activity title |
| `uri` | string | Yes | YouTube or Vimeo URL |
| `type` | enum | Yes | `"youtube"` or `"vimeo"` |
| `chapter_id` | string | Yes | Numeric chapter ID, sent as a string |
| `details` | string | No | JSON-encoded player options (same keys as above), defaults to `"{}"` |
The persisted `content` is `{ uri, type, activity_uuid }`.
## Document activities
`activity_type: "TYPE_DOCUMENT"`.
### PDF (`SUBTYPE_DOCUMENT_PDF`)
**Create endpoint:** `POST /api/v1/activities/documentpdf`
```bash
curl -X POST "http://localhost:1338/api/v1/activities/documentpdf" \
-H "Authorization: Bearer lh_your_api_token" \
-F 'name=Course syllabus' \
-F 'chapter_id=7' \
-F 'pdf_file=@./syllabus.pdf;type=application/pdf'
```
`Content-Type` must be `application/pdf`. The persisted `content` is:
```json
{
"filename": "9325f6f7-...-d4ecbfdc89c1_documentpdf.pdf",
"activity_uuid": "activity_37d02abc-..."
}
```
The viewer renders the PDF with PDF.js.
### Generic document (`SUBTYPE_DOCUMENT_DOC`)
Reserved sub-type. There is no dedicated upload endpoint -- if you need to host arbitrary downloadable files, use a hosted-video-style upload via the editor UI, or wrap the file in a Block and reference it from a dynamic page.
## Assignments
`activity_type: "TYPE_ASSIGNMENT"`, `activity_sub_type: "SUBTYPE_ASSIGNMENT_ANY"`.
<Callout type="warning">
**An assignment activity on its own is an empty box.** The activity record is just a placeholder -- the title, description, due date, grading type, and any submission tasks live in a separate `Assignment` record. If you create the activity but skip the second step, learners see a blank panel. Treat both calls as a single transaction in your migration script.
</Callout>
An assignment is a **three-step** create when you want learners to actually submit something:
### Step 1 -- Create the activity shell
Generic `POST /api/v1/activities/`:
```json
{
"name": "Final assignment",
"chapter_id": 7,
"activity_type": "TYPE_ASSIGNMENT",
"activity_sub_type": "SUBTYPE_ASSIGNMENT_ANY",
"content": {},
"published": true
}
```
Capture `id` and `activity_uuid` from the response.
### Step 2 -- Create the linked Assignment record
`POST /api/v1/assignments/` with the assignment metadata. **All numeric IDs are required**:
```json
{
"title": "Final assignment",
"description": "Submit your final project.",
"due_date": "2026-12-31",
"grading_type": "PERCENTAGE",
"published": true,
"org_id": 1,
"course_id": 17,
"chapter_id": 7,
"activity_id": 145,
"auto_grading": false,
"anti_copy_paste": false,
"show_correct_answers": false
}
```
| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `title` | string | Yes | Shown in the assignment header |
| `description` | string | Yes | Body text |
| `due_date` | string (`YYYY-MM-DD`) | Yes | -- |
| `grading_type` | enum | Yes | `ALPHABET`, `NUMERIC`, `PERCENTAGE`, `PASS_FAIL`, `GPA_SCALE` |
| `org_id` / `course_id` / `chapter_id` / `activity_id` | int | Yes | All four foreign keys are required |
| `published` | boolean | No | Defaults `false` |
| `auto_grading` / `anti_copy_paste` / `show_correct_answers` | boolean | No | All default `false` |
The response includes `assignment_uuid`, which is the handle for step 3.
### Step 3 -- Add at least one Task
Without tasks, the assignment renders the description but has no submission UI. `POST /api/v1/assignments/{assignment_uuid}/tasks`:
```json
{
"title": "Submit your project file",
"description": "Upload a PDF of your final project.",
"hint": "Use a clear filename.",
"assignment_type": "FILE_SUBMISSION",
"contents": {},
"max_grade_value": 100
}
```
| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `title` | string | Yes | -- |
| `description` | string | Yes | -- |
| `hint` | string | Yes | Pass `""` if you don't want a hint -- the field is required by the model |
| `assignment_type` | enum | Yes | See list below |
| `contents` | object | No (default `{}`) | Type-dependent payload |
| `max_grade_value` | int | No (default `100`) | Tasks are graded out of this value; new code uses `100` everywhere |
| `reference_file` | string | No | Reference document URL or filename |
Task types (`assignment_type`): `FILE_SUBMISSION`, `QUIZ`, `FORM`, `CODE`, `SHORT_ANSWER`, `NUMBER_ANSWER`, `OTHER`. Each task type interprets `contents` differently -- the safest path for unknown types is `{}`. See the `/api/v1/assignments/` endpoint group in Swagger UI for the per-type contents schema.
<Callout type="warning">
**Assignments require authentication to view**, even on a public course. The `/api/v1/assignments/*` router has a router-level `Depends(require_authenticated_user)` that returns `401` for anonymous requests, so an unauthenticated viewer of a public course sees an **empty panel** where the assignment widget would be. The course outline still lists the assignment activity, but the assignment's title, description, due date, tasks and submission UI only appear after login. There is no public read mode for assignments today -- if learners need to read the assignment description without signing in, surface it in a sibling dynamic page instead.
</Callout>
## Custom
`activity_type: "TYPE_CUSTOM"`, `activity_sub_type: "SUBTYPE_CUSTOM"`.
A free-form activity. `content` is any JSON object you want -- the platform stores it verbatim and exposes it to a custom renderer that you supply on the frontend. Use this when no built-in type fits and you have your own UI for the activity.
```json
{
"name": "Custom widget",
"chapter_id": 7,
"activity_type": "TYPE_CUSTOM",
"activity_sub_type": "SUBTYPE_CUSTOM",
"content": { "anything": "you want", "shape": [1, 2, 3] }
}
```
<Callout type="warning">
**Stock LearnHouse has no built-in renderer for `TYPE_CUSTOM`.** The activity will appear as an empty container in the learner viewer until you ship a custom frontend component for it. Treat `TYPE_CUSTOM` as a hook for your own integration code -- if you don't already have that integration, prefer `SUBTYPE_DYNAMIC_PAGE` (TipTap) or `SUBTYPE_DYNAMIC_EMBED` (iframe) instead.
</Callout>
## SCORM
`activity_type: "TYPE_SCORM"`, sub-types `SUBTYPE_SCORM_12` and `SUBTYPE_SCORM_2004`.
SCORM packages are uploaded through the editor UI -- the manifest (`imsmanifest.xml`) is parsed, files are extracted to storage, and the `content` is populated with launch metadata. Programmatic creation of SCORM activities is not currently exposed as a documented public endpoint; check the Swagger UI on a development instance for the latest interface.
## The full enum (verbatim)
Reproduced from `apps/api/src/db/courses/activities.py`:
```python
class ActivityTypeEnum(str, Enum):
TYPE_VIDEO = "TYPE_VIDEO"
TYPE_DOCUMENT = "TYPE_DOCUMENT"
TYPE_DYNAMIC = "TYPE_DYNAMIC"
TYPE_ASSIGNMENT = "TYPE_ASSIGNMENT"
TYPE_CUSTOM = "TYPE_CUSTOM"
TYPE_SCORM = "TYPE_SCORM"
class ActivitySubTypeEnum(str, Enum):
# Dynamic
SUBTYPE_DYNAMIC_PAGE = "SUBTYPE_DYNAMIC_PAGE"
SUBTYPE_DYNAMIC_MARKDOWN = "SUBTYPE_DYNAMIC_MARKDOWN"
SUBTYPE_DYNAMIC_EMBED = "SUBTYPE_DYNAMIC_EMBED"
# Video
SUBTYPE_VIDEO_YOUTUBE = "SUBTYPE_VIDEO_YOUTUBE"
SUBTYPE_VIDEO_HOSTED = "SUBTYPE_VIDEO_HOSTED"
# Document
SUBTYPE_DOCUMENT_PDF = "SUBTYPE_DOCUMENT_PDF"
SUBTYPE_DOCUMENT_DOC = "SUBTYPE_DOCUMENT_DOC"
# Assignment
SUBTYPE_ASSIGNMENT_ANY = "SUBTYPE_ASSIGNMENT_ANY"
# Custom
SUBTYPE_CUSTOM = "SUBTYPE_CUSTOM"
# SCORM
SUBTYPE_SCORM_12 = "SUBTYPE_SCORM_12"
SUBTYPE_SCORM_2004 = "SUBTYPE_SCORM_2004"
class ActivityLockType(str, Enum):
PUBLIC = "public" # anyone, including anonymous, can view
AUTHENTICATED = "authenticated" # must be signed in
RESTRICTED = "restricted" # only members of assigned usergroups
```

View File

@@ -0,0 +1,269 @@
import { Callout } from 'nextra/components'
# AI-Assisted Migration
LearnHouse exposes a three-call API that uploads a folder of media files, asks Gemini to organise them into chapters and activities, and then creates the entire course in a single transaction. This is the right path when you have a directory full of legacy lecture recordings, PDFs, and images but no existing structure.
All three endpoints live under `/api/v1/courses/migrate/`. They require an **authenticated user session (JWT)** with permission to create courses in the target organization.
<Callout type="warning">
**API tokens are blocked here.** Unlike the standard course/chapter/activity endpoints, the migration endpoints reject requests authenticated with an `lh_*` API token (`HTTP 403: API tokens cannot access this resource. Only user authentication is allowed.`). If you only have an API token, use the **admin token-swap** to mint a JWT first:
```bash
JWT=$(curl -s -X POST 'http://localhost:1338/api/v1/admin/{org_slug}/auth/token' \
-H 'Authorization: Bearer lh_your_api_token' \
-H 'Content-Type: application/json' \
-d '{"user_id": 1}' | jq -r .access_token)
# Now use $JWT for the migrate/* calls
curl -X POST "http://localhost:1338/api/v1/courses/migrate/upload?org_id=1" \
-H "Authorization: Bearer $JWT" -F 'files=@./video.mp4'
```
The token-swap endpoint requires the API token to have the `users.action_read` permission and the target user must belong to the same organization.
</Callout>
## When to use this vs. programmatic migration
| Situation | Use |
| --- | --- |
| You have a clean export from another LMS with a known chapter / activity layout | [Programmatic Migration](/developers/migration/programmatic) |
| You need every detail of the resulting tree to be exact (titles, ordering, types) | Programmatic |
| You have a pile of files and want LearnHouse to propose a structure | AI-assisted (this page) |
| You want to author rich-text dynamic pages | Programmatic (AI-assisted produces media-only activities) |
<Callout type="warning">
The assisted flow only handles **media files** -- video, PDF, image, and audio. It does not import HTML, Markdown, or rich-text content into dynamic pages. For text-heavy migrations, write a programmatic script.
</Callout>
## Supported file types
| Extension | Resulting activity | Sub-type |
| --- | --- | --- |
| `mp4`, `webm`, `mov` | `TYPE_VIDEO` | `SUBTYPE_VIDEO_HOSTED` |
| `pdf` | `TYPE_DOCUMENT` | `SUBTYPE_DOCUMENT_PDF` |
| `png`, `jpg`, `jpeg`, `webp` | `TYPE_DYNAMIC` (image block) | `SUBTYPE_DYNAMIC_PAGE` |
| `mp3`, `wav` | `TYPE_DYNAMIC` (audio block) | `SUBTYPE_DYNAMIC_PAGE` |
Files with any other extension are skipped. Per-file size limit is **5 GB**, and total upload size per migration is **20 GB**.
## Endpoint overview
| # | Method | Path | Purpose |
| --- | --- | --- | --- |
| 1 | `POST` | `/api/v1/courses/migrate/upload?org_id={org_id}` | Upload one or more files to a temporary holding area. Returns a `temp_id`. |
| 2 | `POST` | `/api/v1/courses/migrate/suggest?org_id={org_id}` | Ask Gemini to propose a course tree from the uploaded files. Returns the structure for you to review. |
| 3 | `POST` | `/api/v1/courses/migrate/create?org_id={org_id}` | Commit the (possibly edited) structure: creates the course, chapters, activities, and uploads each file to its final destination. |
Temporary uploads older than 60 minutes are garbage-collected automatically, so finish a migration in one sitting.
## Step 1 -- Upload files
Upload up to 20 GB of files in one or more requests. Pass `temp_id` on subsequent requests to append to the same migration package:
```bash
# First batch -- creates a new temp_id
curl -X POST "http://localhost:1338/api/v1/courses/migrate/upload?org_id=1" \
-H "Authorization: Bearer lh_your_api_token" \
-F 'files=@./lectures/lesson-01.mp4' \
-F 'files=@./lectures/lesson-02.mp4' \
-F 'files=@./handouts/syllabus.pdf'
```
Response:
```json
{
"temp_id": "9c4e3...-d8f1-4...",
"files": [
{
"file_id": "f1a2b3...",
"filename": "lesson-01.mp4",
"file_type": "video/mp4",
"size": 41943040,
"extension": "mp4"
},
...
],
"skipped": []
}
```
Append more files to the same `temp_id`:
```bash
curl -X POST "http://localhost:1338/api/v1/courses/migrate/upload?org_id=1&temp_id=9c4e3...-d8f1-4..." \
-H "Authorization: Bearer lh_your_api_token" \
-F 'files=@./images/diagram-01.png'
```
`skipped` lists files rejected because of unsupported extension or size. They do not count against the total but you should re-encode and re-upload if you need them.
<Callout type="info">
The server limits concurrent uploads to **3 simultaneous requests per process**. If you parallelise the upload of a large package, throttle yourself accordingly.
</Callout>
## Step 2 -- Ask for a suggested structure
Send the `temp_id` and a course name; Gemini groups the files into chapters and proposes activity titles:
```bash
curl -X POST "http://localhost:1338/api/v1/courses/migrate/suggest?org_id=1" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"temp_id": "9c4e3...-d8f1-4...",
"course_name": "Introduction to Astronomy",
"description": "Self-paced intro to astronomy concepts."
}'
```
Response:
```json
{
"course_name": "Introduction to Astronomy",
"course_description": "Self-paced intro to astronomy concepts.",
"chapters": [
{
"name": "Foundations",
"activities": [
{
"name": "Course syllabus",
"activity_type": "TYPE_DOCUMENT",
"activity_sub_type": "SUBTYPE_DOCUMENT_PDF",
"file_ids": ["f3c4d5..."]
},
{
"name": "Lecture 1 -- The night sky",
"activity_type": "TYPE_VIDEO",
"activity_sub_type": "SUBTYPE_VIDEO_HOSTED",
"file_ids": ["f1a2b3..."]
}
]
},
{
"name": "The solar system",
"activities": [...]
}
]
}
```
The AI prompt is parameterised by file extensions (see the table at the top of this page), so the suggested types are deterministic per extension; only the **names**, **chapter grouping**, and **ordering** are AI-generated.
If the AI call fails or quota is exhausted, the endpoint falls back to a **flat structure** -- a single chapter named "Content" containing one activity per file, with names derived from filenames. This guarantees you can still complete the migration even if the AI service is degraded.
### Editing the suggestion
The structure is just JSON -- mutate it in your client however you like before posting to step 3. Common edits:
- Rename chapters and activities
- Move activities between chapters (move a `file_ids` entry between activities, or duplicate the activity object)
- Split or merge chapters
- Reorder activities (the order in the array becomes the activity order)
- Drop an activity by removing it from the array (its file will simply not be imported)
The only constraints are that every `file_id` you reference must exist in the manifest, every `activity_type` / `activity_sub_type` must be a valid enum value, and every file should be referenced by **at most one activity** (referencing the same file twice will fail on the second copy).
## Step 3 -- Create the course
Post the (possibly edited) structure back with the same `temp_id`. The server creates the course, chapters, activities, and copies each file from the temporary upload area to its final location -- all in a single database transaction:
```bash
curl -X POST "http://localhost:1338/api/v1/courses/migrate/create?org_id=1" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"temp_id": "9c4e3...-d8f1-4...",
"structure": {
"course_name": "Introduction to Astronomy",
"course_description": "Self-paced intro to astronomy concepts.",
"chapters": [
{
"name": "Foundations",
"activities": [
{
"name": "Course syllabus",
"activity_type": "TYPE_DOCUMENT",
"activity_sub_type": "SUBTYPE_DOCUMENT_PDF",
"file_ids": ["f3c4d5..."]
}
]
}
]
}
}'
```
Response:
```json
{
"course_uuid": "course_b7e1...",
"course_name": "Introduction to Astronomy",
"chapters_created": 3,
"activities_created": 12,
"success": true,
"error": null
}
```
The created course is **unpublished and private** by default (`public: false`, `published: false`). Visit `/{org_slug}/courses/{course_uuid}/edit` in the dashboard to review and publish it, or use `PUT /api/v1/courses/{course_uuid}` to publish programmatically.
If anything fails (database error, file copy failure, missing files), the entire transaction is rolled back and `success` is `false` with the error in `error`. The temporary upload directory is cleaned up either way -- start over from step 1 with a fresh upload.
## End-to-end script (bash)
```bash
#!/usr/bin/env bash
set -euo pipefail
API=http://localhost:1338/api/v1
API_TOKEN=lh_your_api_token # Pro-plan API token
ORG_SLUG=default
ORG_ID=1
USER_ID=1 # the user to act as
COURSE_NAME="Migrated content"
# 0. Swap the API token for a user JWT (migrate/* endpoints reject API tokens)
TOKEN=$(curl -fsS -X POST "$API/admin/$ORG_SLUG/auth/token" \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"user_id\":$USER_ID}" | jq -r .access_token)
# 1. Upload everything in ./content/
UPLOAD_RESP=$(curl -fsS -X POST "$API/courses/migrate/upload?org_id=$ORG_ID" \
-H "Authorization: Bearer $TOKEN" \
$(for f in ./content/*; do echo -n "-F files=@$f "; done))
TEMP_ID=$(echo "$UPLOAD_RESP" | jq -r '.temp_id')
# 2. Suggest structure
STRUCTURE=$(curl -fsS -X POST "$API/courses/migrate/suggest?org_id=$ORG_ID" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"temp_id\":\"$TEMP_ID\",\"course_name\":\"$COURSE_NAME\"}")
# 3. (Optional) Edit the structure here, e.g. with `jq` -- skipped in this example.
# 4. Create the course
curl -fsS -X POST "$API/courses/migrate/create?org_id=$ORG_ID" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"temp_id\":\"$TEMP_ID\",\"structure\":$STRUCTURE}"
```
## Cleaning up
If you abandon a migration mid-way, the temporary directory is deleted automatically after 60 minutes by the periodic cleanup task. There is no public endpoint to delete a `temp_id` early -- if you need to retry immediately, just start a new upload (you will get a new `temp_id`).
A successfully completed migration leaves no temporary state behind: step 3 deletes the temp directory once the transaction commits.
## Limitations
- **Media only.** Text content (Markdown, HTML, rich text) is not imported. The dynamic-page activities created from images and audio contain a single block referencing the file; no surrounding prose is generated.
- **Single-chapter fallback.** If Gemini is unavailable, every file lands in one chapter named "Content". You can edit the structure before step 3 to rearrange.
- **No assignments / quizzes / SCORM.** The flow does not infer interactive content from media. Create those separately via the programmatic flow.
- **One file per activity.** Each migrated activity references exactly one source file. If you need an activity that combines multiple files (e.g. a dynamic page with several images), build that with the programmatic flow.
For anything beyond the limits above, drop down to [Programmatic Migration](/developers/migration/programmatic) -- you can also use the assisted flow for the bulk of media and follow up with programmatic calls to add rich-text pages, assignments, and quizzes.

View File

@@ -0,0 +1,139 @@
import { Callout } from 'nextra/components'
# Migrating Content into LearnHouse
This section explains how to bring existing course content into LearnHouse using the public API. There are two supported approaches:
1. **Programmatic Migration** -- you script every step (create the course, then chapters, then activities, then upload files). Use this when you need full control of the resulting structure -- typical for migrating from another LMS where you already know the chapter/activity layout.
2. **AI-Assisted Migration** -- you upload a folder of media (videos, PDFs, images, audio) and LearnHouse asks Gemini to propose a chapter/activity tree. You review and confirm, and a single endpoint creates the entire course in one transaction. Use this when you have a pile of files but no predefined structure.
Both approaches share the same underlying data model -- a Course contains Chapters, and each Chapter contains an ordered list of Activities.
<Callout type="info">
All endpoints below are prefixed with `/api/v1/`. In local development the base URL is `http://localhost:1338/api/v1/`. In production it is served at `/api/v1/` on your instance domain.
</Callout>
## Authentication
Every migration call must be authenticated. There are two token types:
- **JWT access tokens** (`POST /api/v1/auth/login`) -- a user session, 8-hour lifetime, refreshable.
- **API tokens** (Pro plan) -- prefixed with `lh_`, issued per organization, no expiry.
Both are sent the same way:
```bash
curl http://localhost:1338/api/v1/courses/?org_id=1 \
-H "Authorization: Bearer lh_your_api_token_here"
```
API tokens are bound to a single organization at creation time. Any attempt to operate on a different `org_id` is rejected at the auth layer, so a leaked token cannot reach across tenants.
<Callout type="warning">
**API tokens cannot call every endpoint.** A small set of routers -- including the AI-assisted migration endpoints under `/api/v1/courses/migrate/*` and several user-scoped endpoints like `/users/profile` -- explicitly reject API tokens (HTTP 403, `"API tokens cannot access this resource"`). For these calls, you need a user JWT. The supported pattern is the **admin token-swap**: use your API token once to mint a JWT on behalf of any user in your organization, then use that JWT for the protected calls.
```bash
# Mint a user JWT using your API token
curl -X POST 'http://localhost:1338/api/v1/admin/{org_slug}/auth/token' \
-H 'Authorization: Bearer lh_your_api_token' \
-H 'Content-Type: application/json' \
-d '{"user_id": 1}'
# → { "access_token": "eyJ...", "token_type": "bearer", "user_id": 1, "user_uuid": "..." }
```
The minted JWT is a normal user session and works on every endpoint, including the migration endpoints. The API token must have the `users.action_read` permission and the target user must belong to the same organization.
</Callout>
| Endpoint group | API token | JWT |
| --- | --- | --- |
| `POST /courses/`, `PUT /courses/{uuid}`, `DELETE /courses/{uuid}` | ✓ | ✓ |
| `POST /chapters/`, `PUT /chapters/{id}/...`, `DELETE /chapters/{id}` | ✓ | ✓ |
| `POST /activities/`, `/activities/video`, `/activities/external_video`, `/activities/documentpdf` | ✓ | ✓ |
| `POST /blocks/{image,video,pdf,audio}` | ✗ | ✓ |
| `POST /assignments/`, `POST /assignments/{uuid}/tasks` | ✓ | ✓ |
| `POST /courses/migrate/upload` / `/suggest` / `/create` | ✗ | ✓ |
The blocks router has `Depends(get_non_api_token_user)` at the router level, so even though individual block handlers accept anonymous + JWT users, an `lh_*` API token is rejected with `403 "API tokens cannot access this resource"`. The same is true for the AI-assisted migration endpoints. For both, use the admin token-swap to mint a JWT first (see callout above).
See [Authentication](/developers/api/authentication) for token issuance.
## The data model in one diagram
```
Organization (org_id)
└── Course (course_uuid, course_id)
└── Chapter (chapter_uuid, chapter_id)
└── Activity (activity_uuid, activity_id)
└── (optional) Block (block_uuid) ← media files referenced from a dynamic page
```
Two ID conventions to keep straight:
- **`*_uuid`** strings (e.g. `course_uuid`, `activity_uuid`, `chapter_uuid`) are the public identifiers used in URLs and most `GET` endpoints.
- **`*_id`** integers (e.g. `course_id`, `chapter_id`) are the internal primary keys. They are required when **creating** a child resource (a chapter needs `course_id`, an activity needs `chapter_id`).
Both are returned in every create response, so capture them as you go.
## Activity types at a glance
| `activity_type` | `activity_sub_type` | What it is | How content is supplied |
| --- | --- | --- | --- |
| `TYPE_DYNAMIC` | `SUBTYPE_DYNAMIC_PAGE` | Rich-text page (TipTap / ProseMirror) | JSON document in `content` |
| `TYPE_DYNAMIC` | `SUBTYPE_DYNAMIC_MARKDOWN` | Page rendered from a remote Markdown URL | `content: { markdown_url }` |
| `TYPE_DYNAMIC` | `SUBTYPE_DYNAMIC_EMBED` | Iframe embed (Google Doc, Notion, etc.) | `content: { embed_url }` |
| `TYPE_VIDEO` | `SUBTYPE_VIDEO_HOSTED` | Self-hosted video file | Multipart upload to `/activities/video` |
| `TYPE_VIDEO` | `SUBTYPE_VIDEO_YOUTUBE` | Embedded YouTube / Vimeo video | JSON `POST /activities/external_video` |
| `TYPE_DOCUMENT` | `SUBTYPE_DOCUMENT_PDF` | PDF document | Multipart upload to `/activities/documentpdf` |
| `TYPE_DOCUMENT` | `SUBTYPE_DOCUMENT_DOC` | Generic document | Reserved -- not exposed via dedicated upload endpoint |
| `TYPE_ASSIGNMENT` | `SUBTYPE_ASSIGNMENT_ANY` | Graded assignment with tasks | Three-step: activity shell + assignment record + at least one task |
| `TYPE_CUSTOM` | `SUBTYPE_CUSTOM` | Free-form structured content | JSON `content` of any shape |
| `TYPE_SCORM` | `SUBTYPE_SCORM_12` / `SUBTYPE_SCORM_2004` | SCORM packages | Reserved -- handled via the SCORM uploader |
The full per-type `content` JSON schemas, including the dynamic page block list, are documented in [Activity Types Reference](/developers/migration/activity-types).
## Quick start: the four building blocks
A complete migration boils down to four call types, in order:
1. **Create a course.** `POST /api/v1/courses/?org_id={org_id}` (multipart). Capture `course_uuid` and `id` from the response.
2. **Create chapters.** `POST /api/v1/chapters/` (JSON), one per chapter, passing `course_id` and `org_id`. Capture each chapter's `id`.
3. **Create activities.** Either the generic `POST /api/v1/activities/` (JSON, for dynamic / embed / markdown / custom / assignment shells) or one of the typed endpoints `/activities/video`, `/activities/external_video`, `/activities/documentpdf` (multipart, for hosted media).
4. **(Optional) Upload media blocks** referenced from a dynamic page via `/api/v1/blocks/{image,video,pdf,audio}` (multipart) and embed them in the page's TipTap content.
A copy-pasteable bash script for the full flow lives in [Programmatic Migration](/developers/migration/programmatic).
## Common pitfalls
<Callout type="warning">
**`chapter_id` and `course_id` are integers, not UUIDs.** Many `GET` endpoints take a UUID, but every `create` body wants the integer primary key. Read it from the previous response's `id` field, not its `chapter_uuid` / `course_uuid` field.
</Callout>
<Callout type="warning">
**Activity type is immutable.** You cannot change `activity_type` or `activity_sub_type` after creation. Delete and recreate the activity if you picked the wrong type.
</Callout>
<Callout type="warning">
**Modifying `content` creates a new version.** Each `PUT /api/v1/activities/{activity_uuid}` that touches `content` increments the activity's `current_version`. This is normal -- learners always see the published version -- but expect your migration to leave a tidy version history.
</Callout>
<Callout type="info">
**Set `published: false` while migrating** and flip it to `true` only once you have spot-checked the result. Unpublished activities are returned by `GET /courses/{course_uuid}/meta?with_unpublished_activities=true` so you can preview the final tree before exposing it to learners.
</Callout>
<Callout type="warning">
**Typed-upload endpoints (`/activities/video`, `/activities/external_video`, `/activities/documentpdf`) always create activities with `published: false` regardless of any payload field.** Follow the create call with `PUT /api/v1/activities/{activity_uuid}` setting `{"published": true}` to publish them. Only the generic `POST /activities/` honours `published` on creation.
</Callout>
<Callout type="warning">
**`TYPE_ASSIGNMENT` is a three-step create.** A bare assignment activity renders as an empty panel. You also need to `POST /api/v1/assignments/` to attach the title/description/grading, and at least one `POST /api/v1/assignments/{uuid}/tasks` for a submission UI. See [Activity Types Reference -- Assignments](/developers/migration/activity-types#assignments).
</Callout>
<Callout type="warning">
**`TYPE_CUSTOM` has no built-in renderer.** A custom activity will appear as an empty container in the learner viewer until you ship your own React component for it. Prefer `SUBTYPE_DYNAMIC_PAGE` (TipTap) or `SUBTYPE_DYNAMIC_EMBED` (iframe) unless you specifically have custom frontend code in place.
</Callout>
## Where to next
- [Programmatic Migration](/developers/migration/programmatic) -- step-by-step guide with curl examples for each call.
- [Activity Types Reference](/developers/migration/activity-types) -- the exact `content` JSON shape for every activity sub-type, including TipTap blocks for dynamic pages.
- [AI-Assisted Migration](/developers/migration/assisted) -- the three-call upload / suggest / create flow for bulk file imports.

View File

@@ -0,0 +1,588 @@
import { Callout } from 'nextra/components'
# Programmatic Migration
This guide walks through the full sequence of API calls needed to build a course from scratch -- the same calls the LearnHouse web UI makes when an editor clicks through the dashboard. Use it as a reference when writing your own migration script.
The base URL in every example is `http://localhost:1338/api/v1` -- replace it with your instance domain.
<Callout type="info">
All examples use an API token (`Authorization: Bearer lh_...`). A user JWT works identically.
</Callout>
## 1. Create the course
```bash
curl -X POST "http://localhost:1338/api/v1/courses/?org_id=1" \
-H "Authorization: Bearer lh_your_api_token" \
-F 'name=Introduction to Python' \
-F 'description=A beginner-friendly Python course' \
-F 'public=false' \
-F 'about=Hands-on Python from zero to writing your first scripts.' \
-F 'thumbnail_type=image' \
-F 'thumbnail=@./thumbnail.png'
```
`org_id` is a query parameter on the create endpoint. The body is **multipart form data** because the same call optionally uploads a thumbnail image or video.
| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `name` | string | Yes | Course title |
| `description` | string | Yes | Short description (one-liner) |
| `about` | string | Yes | Long-form description shown on the course page |
| `public` | boolean | Yes | `true` = listed publicly, `false` = members only |
| `thumbnail_type` | enum | No | `image` (default) or `video` |
| `thumbnail` | file | No | Image or video file matching `thumbnail_type` |
| `learnings` | string | No | JSON-encoded array of learning objectives |
| `tags` | string | No | JSON-encoded array of tags |
The response is a `CourseRead`:
```json
{
"id": 42,
"course_uuid": "course_8e3...",
"org_id": 1,
"name": "Introduction to Python",
"description": "A beginner-friendly Python course",
"about": "Hands-on Python from zero to writing your first scripts.",
"public": false,
"published": false,
"thumbnail_type": "image",
"thumbnail_image": "thumbnail.png",
"thumbnail_video": "",
"creation_date": "2026-04-25 10:00:00",
"update_date": "2026-04-25 10:00:00",
"authors": [...]
}
```
**Capture both `id` and `course_uuid`.** You will need `id` (integer) to create chapters, and `course_uuid` to fetch, update, or delete the course later.
## 2. Create chapters
Chapters are created one at a time with a JSON body:
```bash
curl -X POST "http://localhost:1338/api/v1/chapters/" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"name": "Chapter 1 — Getting set up",
"description": "Install Python, pick an editor, write hello world.",
"course_id": 42,
"org_id": 1,
"lock_type": "public"
}'
```
| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `name` | string | Yes | Chapter title |
| `course_id` | integer | Yes | Course primary key from step 1 |
| `org_id` | integer | Yes | Same org as the course |
| `description` | string | No | Short description |
| `thumbnail_image` | string | No | URL or path to a thumbnail |
| `lock_type` | enum | No | `public` (default), `authenticated`, or `restricted` |
Response (`ChapterRead`):
```json
{
"id": 7,
"chapter_uuid": "chapter_4d1...",
"name": "Chapter 1 — Getting set up",
"description": "Install Python, pick an editor, write hello world.",
"course_id": 42,
"org_id": 1,
"lock_type": "public",
"is_locked": false,
"activities": [],
"creation_date": "...",
"update_date": "..."
}
```
Capture `id` -- it is the `chapter_id` you will pass when creating activities.
<Callout type="info">
Chapters appear in the order they are created. To rearrange them later (or to reorder activities inside a chapter), call `PUT /api/v1/chapters/course/{course_uuid}/order` with the desired ordering. See [Reordering](#reordering) below.
</Callout>
## 3. Create activities
There are three families of activity-create endpoints, depending on the activity type:
### 3a. Generic JSON create -- `POST /api/v1/activities/`
Use this for **dynamic pages, markdown pages, embeds, assignments (shell), and custom activities**. The body is `ActivityCreate`:
```bash
curl -X POST "http://localhost:1338/api/v1/activities/" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"name": "Hello, world",
"chapter_id": 7,
"activity_type": "TYPE_DYNAMIC",
"activity_sub_type": "SUBTYPE_DYNAMIC_PAGE",
"content": {},
"details": {},
"published": false,
"lock_type": "public"
}'
```
| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `name` | string | Yes | Activity title |
| `chapter_id` | integer | Yes | Chapter primary key from step 2 |
| `activity_type` | enum | No (default `TYPE_CUSTOM`) | Always set this explicitly -- the default is rarely what you want. See [Activity Types Reference](/developers/migration/activity-types) |
| `activity_sub_type` | enum | No (default `SUBTYPE_CUSTOM`) | Sub-type for the chosen `activity_type`; the default pairs with `TYPE_CUSTOM` and won't render in the stock viewer |
| `content` | object | No (default `{}`) | Per-type JSON payload (see reference). Always required in practice for every type except a freshly-shelled assignment. |
| `details` | object | No | Per-type metadata (e.g. video player options) |
| `published` | boolean | No | Defaults to `false` |
| `lock_type` | enum | No | `public`, `authenticated`, or `restricted` |
The response is an `ActivityRead`. Capture `id` and `activity_uuid` -- you will need `activity_uuid` if you plan to upload media blocks for a dynamic page, and to update `content` later.
### 3b. Hosted video upload -- `POST /api/v1/activities/video`
Multipart form data. Creates a `TYPE_VIDEO` / `SUBTYPE_VIDEO_HOSTED` activity in one call:
```bash
curl -X POST "http://localhost:1338/api/v1/activities/video" \
-H "Authorization: Bearer lh_your_api_token" \
-F 'name=Lesson 1 walkthrough' \
-F 'chapter_id=7' \
-F 'video_file=@./lesson-01.mp4;type=video/mp4' \
-F 'details={"startTime":0,"endTime":null,"autoplay":false,"muted":false}'
```
`chapter_id` is sent as a string in the form -- it is parsed to an integer server-side.
<Callout type="warning">
The endpoint validates `Content-Type` strictly: only `video/mp4` and `video/webm` are accepted. Curl's automatic content-type detection works for real `.mp4` / `.webm` files, but if the upload is rejected with `"Video : Wrong video format"`, append `;type=video/mp4` (or `video/webm`) to the `-F` argument to set it explicitly.
</Callout>
### 3c. External video -- `POST /api/v1/activities/external_video`
JSON body. Creates a `TYPE_VIDEO` / `SUBTYPE_VIDEO_YOUTUBE` activity that embeds an external player:
```bash
curl -X POST "http://localhost:1338/api/v1/activities/external_video" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"name": "Intro lecture",
"uri": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"type": "youtube",
"chapter_id": "7",
"details": "{\"startTime\":0,\"endTime\":null,\"autoplay\":false,\"muted\":false}"
}'
```
`type` accepts `"youtube"` or `"vimeo"`. `chapter_id` and `details` are both **strings** for this endpoint -- `details` is a JSON-encoded string that the server parses.
### 3d. PDF document -- `POST /api/v1/activities/documentpdf`
Multipart form data. Creates a `TYPE_DOCUMENT` / `SUBTYPE_DOCUMENT_PDF` activity:
```bash
curl -X POST "http://localhost:1338/api/v1/activities/documentpdf" \
-H "Authorization: Bearer lh_your_api_token" \
-F 'name=Course syllabus' \
-F 'chapter_id=7' \
-F 'pdf_file=@./syllabus.pdf;type=application/pdf'
```
<Callout type="warning">
`Content-Type` must be exactly `application/pdf`, otherwise the server returns `"Pdf : Wrong pdf format"`. As with video uploads, curl auto-detects this for real PDFs but `;type=application/pdf` makes it explicit.
</Callout>
### 3e. Assignments (three-step)
An assignment is **never just an activity**. It is an activity shell + an `Assignment` record + at least one `AssignmentTask`. Skip any of those steps and learners see a blank panel. Full sequence:
```bash
# 1. Activity shell
ACT=$(curl -fsS -X POST "http://localhost:1338/api/v1/activities/" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"name": "Final project",
"chapter_id": 7,
"activity_type": "TYPE_ASSIGNMENT",
"activity_sub_type": "SUBTYPE_ASSIGNMENT_ANY",
"content": {},
"published": true
}')
ACT_ID=$(echo "$ACT" | jq -r .id)
# 2. Assignment record (all four foreign keys are required)
ASSIGN=$(curl -fsS -X POST "http://localhost:1338/api/v1/assignments/" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d "{
\"title\":\"Final project\",
\"description\":\"Submit your final project.\",
\"due_date\":\"2026-12-31\",
\"grading_type\":\"PERCENTAGE\",
\"published\":true,
\"org_id\":1,
\"course_id\":42,
\"chapter_id\":7,
\"activity_id\":$ACT_ID
}")
ASSIGN_UUID=$(echo "$ASSIGN" | jq -r .assignment_uuid)
# 3. At least one task — without this the assignment renders without a submission UI
curl -fsS -X POST "http://localhost:1338/api/v1/assignments/$ASSIGN_UUID/tasks" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"title":"Submit your project file",
"description":"Upload a PDF of your final project.",
"hint":"Use a clear filename.",
"assignment_type":"FILE_SUBMISSION",
"contents":{},
"max_grade_value":100
}'
```
See [Activity Types Reference -- Assignments](/developers/migration/activity-types#assignments) for the full field list, supported `grading_type` values, and `assignment_type` task types (`FILE_SUBMISSION`, `QUIZ`, `FORM`, `CODE`, `SHORT_ANSWER`, `NUMBER_ANSWER`, `OTHER`).
## 4. (Optional) Add media blocks to a dynamic page
For `SUBTYPE_DYNAMIC_PAGE` activities, images / videos / PDFs / audio can be embedded inline. The recommended flow is:
1. Upload the file to a Block via `POST /api/v1/blocks/{image|video|pdf|audio}`.
2. Embed the returned `BlockRead` object as the `blockObject` attribute of a TipTap node inside the activity's `content`.
3. Persist the updated `content` via `PUT /api/v1/activities/{activity_uuid}`.
Upload an image block (note: the blocks router rejects API tokens — use a JWT, e.g. one minted via the admin token-swap documented in [Overview → Authentication](/developers/migration#authentication)):
```bash
curl -X POST "http://localhost:1338/api/v1/blocks/image" \
-H "Authorization: Bearer $JWT" \
-F 'activity_uuid=activity_91c...' \
-F 'file_object=@./diagram.png'
```
Response:
```json
{
"id": 13,
"block_uuid": "block_2a8...",
"block_type": "BLOCK_IMAGE",
"content": {
"file_id": "90b8f12e-fb6b-4726-85ef-f6b511e319e5_block_2a8...",
"file_format": "png",
"file_name": "diagram.png",
"file_size": 24576,
"file_type": "image/png",
"activity_uuid": "activity_91c..."
},
"org_id": 1,
"course_id": 42,
"chapter_id": null,
"activity_id": 99,
"creation_date": "...",
"update_date": "..."
}
```
`content.file_id` is a compound identifier (a UUID, an underscore, then the block UUID). Treat it as opaque -- the renderer uses it as-is to fetch the asset from `/api/v1/content/...`.
You can then reference this block from a TipTap `blockImage` node inside the activity's `content`. See [Activity Types Reference -- Dynamic Page](/developers/migration/activity-types#dynamic-page-subtype_dynamic_page) for the exact node shape.
The four block endpoints are symmetric:
| Endpoint | Allowed file extensions | Resulting `block_type` |
| --- | --- | --- |
| `POST /api/v1/blocks/image` | `jpg, jpeg, png, gif, webp` | `BLOCK_IMAGE` |
| `POST /api/v1/blocks/video` | `mp4, webm, ogg` | `BLOCK_VIDEO` |
| `POST /api/v1/blocks/pdf` | `pdf` | `BLOCK_DOCUMENT_PDF` |
| `POST /api/v1/blocks/audio` | `mp3, wav, ogg, m4a` | `BLOCK_AUDIO` |
All four take the same form fields: `file_object` (the file) and `activity_uuid` (the parent activity).
## 5. Update an activity's content
After creating a dynamic-page activity (`content: {}`), upload any media blocks, then `PUT` the full TipTap document:
```bash
curl -X PUT "http://localhost:1338/api/v1/activities/activity_91c..." \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"content": {
"type": "doc",
"content": [
{ "type": "heading", "attrs": { "level": 1 },
"content": [{ "type": "text", "text": "Hello, world" }] },
{ "type": "paragraph",
"content": [{ "type": "text", "text": "Welcome to the course." }] }
]
}
}'
```
The full list of valid TipTap node types is in [Activity Types Reference](/developers/migration/activity-types#valid-tiptap-block-types).
`ActivityUpdate` accepts a partial body -- only fields you set are changed. Updateable fields:
| Field | Type | Notes |
| --- | --- | --- |
| `name` | string | Activity title |
| `content` | object | Replaces the entire content document |
| `details` | object | Replaces the details object |
| `published` | boolean | Flip to `true` when ready to publish |
| `lock_type` | enum | Access control |
| `published_version` / `version` | int | Advanced versioning -- usually leave alone |
`activity_type` and `activity_sub_type` are technically updateable in the schema but should be treated as immutable in practice -- the persisted `content` shape will not match the new type.
## Reordering
Chapters and the activities inside them appear in the order they were created. To explicitly set ordering, call:
```bash
curl -X PUT "http://localhost:1338/api/v1/chapters/course/course_8e3.../order" \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{
"chapter_order_by_ids": [
{ "chapter_id": 7, "activities_order_by_ids": [{"activity_id": 99}, {"activity_id": 100}] },
{ "chapter_id": 8, "activities_order_by_ids": [{"activity_id": 101}] }
]
}'
```
The path takes the `course_uuid`.
<Callout type="warning">
**This endpoint is destructive.** It re-specifies the entire course tree -- every chapter you omit from `chapter_order_by_ids` is unlinked from the course, and every activity you omit from a chapter's `activities_order_by_ids` is unlinked from that chapter. The underlying Activity / Chapter rows are not deleted, but they are removed from the course's table of contents and learners will no longer see them.
Always:
- Fetch the current tree first via `GET /api/v1/courses/{course_uuid}/meta?with_unpublished_activities=true&slim=true`,
- Build the reorder payload from that tree (modifying only the order),
- Then `PUT` it back.
Sending an empty `activities_order_by_ids` for a chapter wipes that chapter's activities from the course.
</Callout>
## Publishing
When the migration is complete, flip the course and each activity to `published: true`:
```bash
# Publish the course
curl -X PUT "http://localhost:1338/api/v1/courses/course_8e3..." \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{ "published": true }'
# Publish an activity
curl -X PUT "http://localhost:1338/api/v1/activities/activity_91c..." \
-H "Authorization: Bearer lh_your_api_token" \
-H "Content-Type: application/json" \
-d '{ "published": true }'
```
To preview unpublished work, fetch the course tree with the `with_unpublished_activities` flag:
```bash
curl "http://localhost:1338/api/v1/courses/course_8e3.../meta?with_unpublished_activities=true" \
-H "Authorization: Bearer lh_your_api_token"
```
## End-to-end script (bash)
The script below creates a complete, public, published course with **one of every activity type** -- a thumbnail, three chapters, a TipTap dynamic page with an embedded image block, a remote-Markdown page, an iframe embed, a hosted MP4, a YouTube embed, a PDF, and a fully-functional assignment with one File Submission task. It is the same flow used to validate this documentation against a live instance.
Save the assets you want to use to a folder (the script expects `thumbnail.jpg`, `diagram.jpg`, `clip.mp4`, `doc.pdf`) and run it. Total runtime is under 10 seconds against a local dev instance.
<Callout type="info">
**Pre-requisites:** `bash`, `curl`, `jq`, and `python3` (for one inline JSON-builder). The script uses the API-token-to-JWT swap so it works with either an `lh_*` API token (the recommended setup) or by replacing `TOKEN=...` with a JWT you already have.
</Callout>
```bash
#!/usr/bin/env bash
# build-demo-course.sh — create a complete course end-to-end via the LearnHouse API.
set -euo pipefail
# ── Config ───────────────────────────────────────────────────────────────────
API=http://localhost:1338/api/v1
API_TOKEN=lh_your_api_token # Pro-plan API token
ORG_SLUG=default # your org slug
ORG_ID=1 # your org id
USER_ID=1 # which user the script acts as
ASSETS=./assets # folder containing thumbnail.jpg, diagram.jpg, clip.mp4, doc.pdf
# ── 0. Mint a user JWT from the API token ───────────────────────────────────
# (Most endpoints accept the API token directly, but the JWT path is universal
# — including the AI-assisted migration endpoints which reject API tokens.)
TOKEN=$(curl -fsS -X POST "$API/admin/$ORG_SLUG/auth/token" \
-H "Authorization: Bearer $API_TOKEN" \
-H 'Content-Type: application/json' \
-d "{\"user_id\":$USER_ID}" | jq -r .access_token)
# Tiny helpers
post_json() { curl -fsS -X POST "$1" -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d "$2"; }
put_json() { curl -fsS -X PUT "$1" -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d "$2"; }
# ── 1. Course (multipart, with a real JPEG thumbnail) ───────────────────────
COURSE=$(curl -fsS -X POST "$API/courses/?org_id=$ORG_ID" \
-H "Authorization: Bearer $TOKEN" \
-F 'name=The Complete Demo Course' \
-F 'description=One of every activity type, built via the API' \
-F 'about=Created end-to-end by the LearnHouse migration quickstart script.' \
-F 'public=true' \
-F 'thumbnail_type=image' \
-F "thumbnail=@$ASSETS/thumbnail.jpg;type=image/jpeg")
CID=$(echo "$COURSE" | jq -r .id)
CUUID=$(echo "$COURSE" | jq -r .course_uuid)
echo "→ course $CUUID (id=$CID)"
# ── 2. Three chapters ───────────────────────────────────────────────────────
CH1_ID=$(post_json "$API/chapters/" \
"{\"name\":\"1. Dynamic content\",\"description\":\"Pages, embeds, markdown\",\"course_id\":$CID,\"org_id\":$ORG_ID}" | jq -r .id)
CH2_ID=$(post_json "$API/chapters/" \
"{\"name\":\"2. Media\",\"description\":\"Hosted video, YouTube, PDF\",\"course_id\":$CID,\"org_id\":$ORG_ID}" | jq -r .id)
CH3_ID=$(post_json "$API/chapters/" \
"{\"name\":\"3. Interactive\",\"description\":\"Assignment\",\"course_id\":$CID,\"org_id\":$ORG_ID}" | jq -r .id)
# ── 3a. Dynamic Page (TipTap content with an embedded image block) ──────────
# Create the activity with empty content first, then upload an image block,
# then PUT the full TipTap document referencing that block.
PAGE=$(post_json "$API/activities/" \
"{\"name\":\"Welcome page\",\"chapter_id\":$CH1_ID,\"activity_type\":\"TYPE_DYNAMIC\",\"activity_sub_type\":\"SUBTYPE_DYNAMIC_PAGE\",\"content\":{},\"published\":true}")
PAGE_UUID=$(echo "$PAGE" | jq -r .activity_uuid)
BLOCK=$(curl -fsS -X POST "$API/blocks/image" \
-H "Authorization: Bearer $TOKEN" \
-F "activity_uuid=$PAGE_UUID" \
-F "file_object=@$ASSETS/diagram.jpg;type=image/jpeg")
echo "$BLOCK" > /tmp/lh-block.json
# Build the TipTap document — the image block is embedded as a `blockImage`
# atom node whose `attrs.blockObject` carries the full BlockRead response.
TIPTAP=$(python3 - <<'PY'
import json
block = json.load(open('/tmp/lh-block.json'))
doc = {
"type": "doc",
"content": [
{"type":"heading","attrs":{"level":1},"content":[{"type":"text","text":"Welcome to the demo course"}]},
{"type":"paragraph","content":[
{"type":"text","text":"This page was created "},
{"type":"text","text":"entirely via the API","marks":[{"type":"bold"}]},
{"type":"text","text":". It uses TipTap blocks: paragraphs, headings, lists, code, and an image block."}
]},
{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"A figure"}]},
{"type":"blockImage","attrs":{"blockObject": block, "size":{"width":500},"alignment":"center"}},
{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"What you will learn"}]},
{"type":"bulletList","content":[
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Programmatic course migration"}]}]},
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Every activity type"}]}]},
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"TipTap content blocks"}]}]}
]},
{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"A code block"}]},
{"type":"codeBlock","attrs":{"language":"python"},
"content":[{"type":"text","text":"def hello():\n print(\"Hello, world!\")\n\nhello()"}]}
]
}
print(json.dumps({"content": doc, "published": True}))
PY
)
put_json "$API/activities/$PAGE_UUID" "$TIPTAP" > /dev/null
# ── 3b. Dynamic Markdown (renders a remote .md URL) ─────────────────────────
post_json "$API/activities/" \
"{\"name\":\"Markdown remote page\",\"chapter_id\":$CH1_ID,\"activity_type\":\"TYPE_DYNAMIC\",\"activity_sub_type\":\"SUBTYPE_DYNAMIC_MARKDOWN\",\"content\":{\"markdown_url\":\"https://raw.githubusercontent.com/anthropics/anthropic-cookbook/main/README.md\"},\"published\":true}" > /dev/null
# ── 3c. Dynamic Embed (iframe) ──────────────────────────────────────────────
post_json "$API/activities/" \
"{\"name\":\"Embed example\",\"chapter_id\":$CH1_ID,\"activity_type\":\"TYPE_DYNAMIC\",\"activity_sub_type\":\"SUBTYPE_DYNAMIC_EMBED\",\"content\":{\"embed_url\":\"https://en.wikipedia.org/wiki/Special:Random\"},\"published\":true}" > /dev/null
# ── 4a. Hosted MP4 (multipart, then PUT to publish) ─────────────────────────
# /activities/video forces published=false on create; we flip it after.
VID=$(curl -fsS -X POST "$API/activities/video" \
-H "Authorization: Bearer $TOKEN" \
-F 'name=Hosted MP4 sample' \
-F "chapter_id=$CH2_ID" \
-F "video_file=@$ASSETS/clip.mp4;type=video/mp4" \
-F 'details={"startTime":0,"endTime":null,"autoplay":false,"muted":false}')
put_json "$API/activities/$(echo "$VID" | jq -r .activity_uuid)" '{"published":true}' > /dev/null
# ── 4b. YouTube external video (JSON, then PUT to publish) ──────────────────
YT=$(post_json "$API/activities/external_video" \
"{\"name\":\"YouTube embed\",\"uri\":\"https://www.youtube.com/watch?v=jNQXAC9IVRw\",\"type\":\"youtube\",\"chapter_id\":\"$CH2_ID\",\"details\":\"{\\\"startTime\\\":0,\\\"endTime\\\":null,\\\"autoplay\\\":false,\\\"muted\\\":false}\"}")
put_json "$API/activities/$(echo "$YT" | jq -r .activity_uuid)" '{"published":true}' > /dev/null
# ── 4c. PDF document (multipart, then PUT to publish) ───────────────────────
PDF=$(curl -fsS -X POST "$API/activities/documentpdf" \
-H "Authorization: Bearer $TOKEN" \
-F 'name=Sample PDF document' \
-F "chapter_id=$CH2_ID" \
-F "pdf_file=@$ASSETS/doc.pdf;type=application/pdf")
put_json "$API/activities/$(echo "$PDF" | jq -r .activity_uuid)" '{"published":true}' > /dev/null
# ── 5. Assignment (THREE-step: shell + record + at least one task) ──────────
ASSIGN_ACT=$(post_json "$API/activities/" \
"{\"name\":\"Final assignment\",\"chapter_id\":$CH3_ID,\"activity_type\":\"TYPE_ASSIGNMENT\",\"activity_sub_type\":\"SUBTYPE_ASSIGNMENT_ANY\",\"content\":{},\"published\":true}")
ASSIGN_ACT_ID=$(echo "$ASSIGN_ACT" | jq -r .id)
ASSIGN=$(post_json "$API/assignments/" \
"{\"title\":\"Final assignment\",\"description\":\"Submit your final project.\",\"due_date\":\"2026-12-31\",\"grading_type\":\"PERCENTAGE\",\"published\":true,\"org_id\":$ORG_ID,\"course_id\":$CID,\"chapter_id\":$CH3_ID,\"activity_id\":$ASSIGN_ACT_ID}")
ASSIGN_UUID=$(echo "$ASSIGN" | jq -r .assignment_uuid)
post_json "$API/assignments/$ASSIGN_UUID/tasks" \
'{"title":"Submit your project file","description":"Upload a PDF of your final project.","hint":"Use a clear filename.","assignment_type":"FILE_SUBMISSION","contents":{},"max_grade_value":100}' > /dev/null
# ── 6. Publish the course ───────────────────────────────────────────────────
put_json "$API/courses/$CUUID" '{"published":true,"public":true}' > /dev/null
# ── 7. Verify ───────────────────────────────────────────────────────────────
echo ""
echo "Tree:"
curl -fsS "$API/courses/$CUUID/meta?with_unpublished_activities=true&slim=true" \
-H "Authorization: Bearer $TOKEN" | jq -r '
"course: \(.name) (public=\(.public), published=\(.published))",
(.chapters[] | " \(.name)",
(.activities[] | " - \(.name) [\(.activity_type)/\(.activity_sub_type)]"))'
echo ""
echo "View it at: http://localhost:3000/course/$(echo $CUUID | sed s/course_//)"
```
What you should see in the browser at the printed URL:
- **Course landing page** with the JPEG thumbnail, three chapters, "7 exciting activities" badge, and a "Start Course" button.
- **Welcome page** with the heading, bold paragraph, embedded image, bullet list, and Python-highlighted code block, plus a TOC sidebar generated from the headings.
- **Markdown remote page** rendering the GitHub README with full formatting.
- **Embed example** showing a Wikipedia article inside an iframe.
- **Hosted MP4 sample** in the LearnHouse video player.
- **YouTube embed** with the YouTube iframe player.
- **Sample PDF document** in the embedded PDF.js viewer with toolbar.
- **Final assignment** showing the description, due date, and File Submission widget -- **but only when signed in**. The `/api/v1/assignments/*` router rejects anonymous requests, so on a public course an anonymous viewer sees a blank panel where the assignment widget would be. Sign in (or open via the dashboard) to see the description, tasks, and submission UI.
## Verifying the result
After migration, fetch the full course tree and inspect it before announcing the course to learners:
```bash
curl "http://localhost:1338/api/v1/courses/$CUUID/meta?with_unpublished_activities=true&slim=true" \
-H "Authorization: Bearer $TOKEN" | jq '
{chapters: (.chapters | length),
activities: (.chapters | map(.activities | length) | add)}'
```
`slim=true` omits the heavy `content` field from each activity, which is much faster when you only want to verify the structure.
If anything is wrong, every resource has a `DELETE` endpoint -- safest is to delete the course (`DELETE /api/v1/courses/{course_uuid}`), which cascades to its chapters, activities, and blocks, and then re-run the script.
```bash
curl -X DELETE "$API/courses/$CUUID" -H "Authorization: Bearer $TOKEN"
```

File diff suppressed because it is too large Load Diff