caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

664 lines
43 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ReelForge v1 REST API Reference
Complete reference for the ReelForge HTTP API. Every route is mounted under the
`/api/v1` prefix by `app/controllers/v1/base.py::new_router()` and wired into the
root router in `app/router.py`. The FastAPI application is assembled in
`app/asgi.py::get_application()`.
This document is generated by reading the controllers directly
(`app/controllers/v1/*.py`) — every path, auth requirement, request field,
response shape and error code below reflects the actual code.
The API currently exposes **109** endpoints across the **22** routers wired into
`root_api_router` in `app/router.py` (in include order): `video`, `llm`, `jobs`,
`studio`, `billing`, `catalog`, `me`, `voices`, `ideas`, `notifications`,
`schedule`, `covers`, `workspaces`, `brand`, `social`, `api_keys`, `analytics`,
`marketplace`, `performance`, `connections`, `share`, `creators`.
---
## 1. Conventions
### 1.1 Base URL & versioning
All ReelForge endpoints live under:
```
/api/v1/...
```
The prefix and the `V1` OpenAPI tag are set once in `new_router()`
(`app/controllers/v1/base.py`). A health probe is served **outside** the version
prefix at `GET /ping` (`app/controllers/ping.py`, returns the literal string
`"pong"`).
Static assets are also mounted at the app root: `GET /tasks/*` (legacy MPT task
artifacts) and `GET /*` (the public SPA), configured in `app/asgi.py`.
### 1.2 Response envelope — `get_response`
Every JSON response uses the shared MPT envelope built by
`app/utils/utils.py::get_response(status, data, message)`:
```python
def get_response(status: int, data=None, message: str = ""):
obj = {"status": status}
if data: # falsy data (None, [], {}, 0) is DROPPED
obj["data"] = data
if message: # empty message is DROPPED
obj["message"] = message
return obj
```
Shape on success:
```json
{ "status": 200, "data": { ... } }
```
> Note: because `get_response` drops **falsy** `data`, an empty-list result
> (e.g. an empty catalog or an empty job list) serializes as `{"status": 200}`
> with no `data` key. Response models default such fields to `[]`.
### 1.3 Error envelope & handlers
Errors are raised as `app/models/exception.py::HttpException` and rendered by the
handlers registered in `app/asgi.py`:
| Handler | Trigger | HTTP | Body |
|---|---|---|---|
| `exception_handler` | any `HttpException` | `e.status_code` | `get_response(status, e.data, e.message)` |
| `validation_exception_handler` | Pydantic `RequestValidationError` | `400` | `get_response(400, e.errors(), "field required")` |
Error body shape:
```json
{ "status": 401, "message": "<request_id>: invalid token: ..." }
```
Note: Pydantic field-shape violations that FastAPI raises before the handler
(`response_model` / `Field` constraint failures on the request body) surface as
the framework default **422**, while validation the controllers perform
explicitly is returned as **400**. Both patterns appear below.
### 1.4 Request / correlation id
Every handler derives a `request_id` via `base.get_task_id(request)`
(`app/controllers/base.py`): the `x-task-id` request header when present, else a
generated UUID. It is echoed into error messages for correlation.
---
## 2. Authentication model
Two auth paths are supported. Which one applies depends on the controller (see
each group's table). Auth helpers live in `app/controllers/base.py` and
`app/core/clerk.py`.
### 2.1 `x-api-key` — global gate (`verify_token`)
`base.verify_token` compares the `x-api-key` header against the single operator
key `config.app["api_key"]`. Applied as a router-level dependency
(`new_router(dependencies=[Depends(base.verify_token)])`) on the **LLM** and
**Workspaces** routers. On mismatch → **401** `invalid token`.
### 2.2 `x-api-key` — per-user resolution (`_resolve_user`)
Most ReelForge endpoints are multi-tenant. Rather than the single global key they
resolve the caller to a `User` row. The canonical resolver is
`app/core/auth/principal.py::resolve_principal()`, reused across the reel, media,
editor, and compatibility controller surfaces,
`me`, `voices`, `ideas`, `notifications`, `schedule`, `covers`, `brand`,
`workspaces`, `social`, and every phase-current controller
(`api_keys`, `analytics`, `marketplace`, `performance`, `connections`, `share`,
`creators`), all of which import the same guard block. It checks two paths in
order:
1. **Clerk JWT** (`_resolve_user_via_clerk`) — an `Authorization: Bearer <jwt>`
header, verified against Clerk's JWKS (RS256) by `app/core/clerk.py`. On first
sight the `sub`/`email` claims are mapped to a `User` row (get-or-create,
keyed on `email` or a `clerk_<sub>@users.reelforge` stand-in). Only attempted
when Clerk is configured (a resolvable `config.clerk.jwks_url` or
`config.clerk.issuer`). A **present but invalid** bearer token → **401**
(it does not silently fall through).
2. **`x-api-key`** — `SHA-256(x-api-key)` matched against `User.api_key_hash`.
Missing header → **401** `missing x-api-key header`; no match → **401**
`invalid api key`. In addition to the built-in per-user key, a caller may
present a **personal API key** minted via `POST /me/api-keys` (§4.16); these
are resolved back to their owning `User` by
`app/controllers/v1/base.py::resolve_user_by_api_key` (SHA-256 digest lookup,
excluding revoked rows) and are subject to per-key rate-limit / monthly-quota
caps (**429** on breach).
When Clerk is not configured the bearer path is inert and behavior is
`x-api-key`-only. `billing.create_checkout` uses its own `x-api-key`-only
resolver (`billing._resolve_user`, no Clerk path).
Clerk config keys (read defensively from `config.clerk`): `jwks_url` or
`issuer` (JWKS derived as `<issuer>/.well-known/jwks.json`), optional `audience`
(only enforced when set), optional `algorithms` (default `["RS256"]`).
### 2.3 Unauthenticated endpoints
`billing.plans`, `billing.providers`, the payment **webhooks** (verified by
provider signature instead), all `catalog/*` reference endpoints, the legacy
`llm.*` share no per-user auth beyond `verify_token`, and the entire legacy
`video.py` router are not per-user gated. See each group below.
Three phase-current routes are also **PUBLIC** (they deliberately skip
`_resolve_user` so they are reachable without any key): the watermarked share
page `GET /public/r/{token}` (§4.21), and the two creator surfaces
`GET /creators/leaderboard` and `GET /creators/{handle_or_id}` (§4.22). Each
returns only a STRICT safe DTO — no result key, `user_id`, email, credits, cost
or revenue can leak.
### 2.4 Degradation (`503`)
Controllers import the persistence / service layers behind guarded blocks so the
app never crashes at import. When a required layer is absent the endpoint returns
**503** (`persistence layer is not available`, `<service> is not available`, …)
rather than a 500. This applies to every DB-backed endpoint below.
---
## 3. Upload presign flow
Client-side uploads to Cloudflare R2 use a presign handshake. There is one
presign endpoint (`jobs.presign_upload`); the returned `key` is then passed to
whichever endpoint consumes an upload.
```
1. POST /api/v1/uploads/presign { filename, content_type, size }
→ { upload_url, get_url, key, headers }
2. PUT <upload_url> (body = file bytes, headers = returned `headers`) [direct to R2]
3. Use `key` in a downstream call:
- jobs params.screen_recording_key / voiceover_key / broll_*_key
- POST /avatars { image_key: key }
- POST /voices/clone { sample_key: key }
- PUT /me/brand { logo_key: key }
```
**Content-type allowlist** (`app/models/schema.py::ALLOWED_UPLOAD_CONTENT_TYPES`,
enforced by `PresignRequest`): `video/mp4`, `video/quicktime`, `video/webm`,
`audio/mpeg`, `audio/wav`, `image/png`, `image/jpeg`. A MIME outside the set is a
**422**.
**Ownership (BOLA) guard.** Uploads are registered as caller-scoped `Asset` rows
(`r2_key` + `user_id`). Any endpoint that consumes a client-supplied R2 key
re-verifies ownership before use (`_verify_image_ownership`,
`_verify_logo_ownership`, the `sample_key` check in `voices.clone`, and the
compose-stage `_assert_owned_r2_key` guard for job keys) → **403** on a
foreign/guessed key. The ownership models fail **closed** (503) if the `Asset`
model is unavailable.
---
## 4. Endpoint groups
Grouped by controller. Unless a row says otherwise, "Per-user" auth = the
Clerk-JWT-or-`x-api-key` resolver from §2.2, and every DB-backed route can return
**503** when its layer is unavailable.
### 4.1 Jobs — `app/domains/reels/router.py`
Core render-pipeline lifecycle. Router: `new_router()` (no router-level
dependency; each handler calls `_resolve_user`). Job cost is `1` credit
(`config.app["reelforge_job_cost"]`). Rate limit for creates/reruns/dubs:
`reelforge_jobs_rate_limit`/`_window_s` (default 30/hour per user); B-roll:
`reelforge_broll_rate_limit`/`_window_s` (default 20/hour).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/uploads/presign` | Per-user | `PresignRequest` `{filename, content_type, size}` | `{upload_url, get_url, key, headers}` | 401 auth; 422 bad content_type; 502 storage; 503 |
| POST | `/api/v1/uploads/register` | Per-user | `{key, kind}` | `{asset_id, key, kind}` | 400 non-upload key; 401; 503 |
| POST | `/api/v1/jobs` | Per-user | `JobCreateRequest` (see below); optional `Idempotency-Key` header (1–128 chars) | `{job_id, state, progress}`; for `variants>1`: `+ {job_ids, batch_id}` | 400 bad params/layout/feature-secret/key; 402 insufficient credits; 403 non-member workspace; 409 same key with different request; 429 rate; 502 enqueue; 503 |
| GET | `/api/v1/jobs` | Per-user | query `limit` (1-100, def 50), `offset` | `{jobs: [JobData]}` | 401; 503 |
| GET | `/api/v1/jobs/{job_id}` | Per-user (owner) | — | `JobData` `{job_id, state, progress, stages, [failed_stage, error, result_url]}` | 404 unknown/foreign; 503 |
| GET | `/api/v1/batches/{batch_id}` | Per-user (owner) | — | `{batch_id, jobs: [{job_id, state, progress, [result_url, poster_key]}]}` | 404 unknown/empty/foreign; 503 |
| POST | `/api/v1/jobs/{job_id}/retry` | Per-user (owner) | — | `{job_id, state, progress}` | 402 credits; 404 unknown/foreign; 409 not in FAILED state; 502 re-enqueue; 503 |
| POST | `/api/v1/jobs/{job_id}/rerun` | Per-user (owner) | `RerunRequest` `{overrides?: RerunOverrides}` | `{job_id, state, progress}` (new job) | 400; 402; 404; 429 rate; 502; 503 |
| POST | `/api/v1/jobs/{job_id}/dub` | Per-user (owner) | `DubRequest` `{languages: [str]}` | `{batch_id, job_ids, languages}` | 400 empty/unsupported/too-many langs (max 12); 402; 404; 409 source has no script; 429; 503 |
| POST | `/api/v1/jobs/{job_id}/broll/suggest` | Per-user (owner) | `BrollSuggestRequest` `{source?, amount? (1-12)}` | `{clips: [{broll_key, duration, source, term}]}` (may be empty) | 404 unknown/foreign; 429 rate; 503 |
| POST | `/api/v1/jobs/{job_id}/exports` | Per-user (owner) | `{in_point, out_point}` + optional `Idempotency-Key` | `{job_id, state, progress, correlation_id}` | 404 unknown/foreign; 409 source not ready/key conflict; 503 |
| POST | `/api/v1/generation/broll/generate` | Per-user | `BrollGenerateRequest` + optional `Idempotency-Key` | async generation snapshot | 400 prompt/workflow; 402 credits; 403 pilot/ownership; 409 key conflict; 429; 502; 503 |
| GET | `/api/v1/generation/broll/generations` | Per-user | query `limit` | caller's durable generation history | 401; 503 |
| GET | `/api/v1/generation/broll/generations/{id}` | Per-user (owner) | — | generation snapshot + signed `result_url` when complete | 404; 503 |
| GET | `/api/v1/avatars` | Per-user | — | list of avatars (`AvatarPreset` rows `source:"preset"` + live HeyGen `source:"provider"`) | 401; 503 |
| GET | `/api/v1/voices` | Per-user | — | curated voice list `[{id, name, language, gender, description, provider}]` (falls back to live ElevenLabs) | 401; 503 |
| GET | `/api/v1/me` | Per-user | — | `{user_id, email, credits, jobs_count}` | 401; 503 |
For a retry-safe reel, B-roll, or editor-export create, send a new
`Idempotency-Key` with the first request
and reuse it only if that exact request must be retried. A matching replay
returns the original creation response without another debit or enqueue; reuse
of the key with a different request is rejected with `409`.
**`JobCreateRequest` fields** (`extra="allow"`; unknown params are filtered
against `ReelForgeParams`):
| Field | Type | Notes |
|---|---|---|
| `params` | object | `ReelForgeParams`-shaped (see below). Validated at handler time. |
| `avatar_id` | str? | folded into `params` |
| `voice_id` | str? | normalized to `elevenlabs:<id>` → `params.voice_name` |
| `caption_style` | str? (≤64) | validated against caption presets → **422** on unknown |
| `music_id`, `music_prompt`, `bgm_provider` | str? | background music (bgm_provider ∈ `elevenlabs`/`sonilo`/`""`) |
| `broll_intro_key`, `broll_outro_key`, `voiceover_key` | str? | R2 keys (ownership-checked at compose time) |
| `webhook_url`, `webhook_secret` | str? | completion callback (HMAC-SHA256) |
| `variants` | int (1-3, def 1) | batch fan-out; N jobs, N credits, shared `batch_id` |
| `tos_disclosure` | bool | mark output as AI/synthetic in cross-post metadata |
| `workspace_id` | str? (≤64) | debit the workspace SHARED pool (requires membership → 403) |
**`ReelForgeParams`** (`app/services/reelforge.py`) — key render fields:
`video_subject` (required), `video_script`, `voice_name` (`elevenlabs:<id>`),
`voice_rate`, `avatar_id`, `avatar_provider` (`heygen`), `caption_style`
(`karaoke_yellow`), `layout` (`pip`|`hook_intro`|`split`), `aspect` (`9:16`),
`language` (`auto`), `target_duration_s` (30), `platforms` (tuple; empty →
skip upload), `youtube_privacy_status`, `screen_recording_key`, `music_*`,
`bgm_provider`, `watermark_*`, `broll_*_key`, `voiceover_key`.
**`RerunOverrides`** (all optional): `avatar_id`, `voice_id`, `layout`,
`caption_style`, `music_id`, `language`.
**Job `state` integers** (`app/models/const.py`): `-1` FAILED, `1` COMPLETE,
`4` PROCESSING.
**Credit invariant**: for create/rerun/dub the N Job rows are persisted and
N×cost credits debited in **one committed transaction** (402 rolls the whole
batch back, enqueuing none) *before* any Celery pipeline is enqueued. A failed
enqueue reconciles that job with a refund + FAILED transition. Workspace jobs
debit/refund the SHARED pool; personal jobs the caller's balance. Retry re-bills
the same pool that funded the original (recovered from the credit ledger).
### 4.2 Studio — `app/controllers/v1/studio.py`
On-demand publish + photo→avatar. Router: `new_router()` (per-user). `GET
/avatars` lives in the jobs controller, not here.
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/jobs/{job_id}/publish` | Per-user (owner) | `PublishRequest` `{platforms: [str], youtube_privacy_status?}` | per-platform publish results | 400 no platforms; 404 unknown/foreign; 409 not complete **or** already published; 429 rate; 502 publish; 503 |
| POST | `/api/v1/avatars` | Per-user | `CreateAvatarRequest` `{image_key, display_name?, voice_name?}` | `{id, provider, provider_avatar_id, display_name, voice_name, thumbnail_url, is_active, kind, source}` | 400 no image_key; 403 image not owned; 502 provider/persist; 503 HeyGen not configured / download dep |
Publish rate limit: `reelforge_publish_rate_limit`/`_window_s` (default 5/hour
per user+job). Publish is idempotent — a completed `publish` `JobEvent` blocks a
repeat (409). `create_avatar` mints a real HeyGen talking-photo from the owned
image and persists an owner-scoped `AvatarPreset` (`kind:"talking_photo"`).
### 4.3 Billing — `app/controllers/v1/billing.py`
Credit purchases + payment webhooks. Router: `new_router()`. Providers:
`stripe`, `iyzico`, `creem`, `polar`. Secrets, signature verification and
Redis-SETNX idempotency live in `app/services/billing/service`.
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| GET | `/api/v1/billing/plans` | None (public) | — | credit-plan catalogue | 502 load; 503 |
| GET | `/api/v1/billing/providers` | None (public) | — | `{providers: [str]}` (only configured rails) | 502; 503 |
| POST | `/api/v1/billing/checkout` | `x-api-key` (own resolver) | `CheckoutRequest` `{provider, plan_key, workspace_id?}` | `{checkout_url}` | 400 bad provider/plan_key; 401; 403 not workspace admin; 404 unknown workspace; 502 provider; 503 |
| POST | `/api/v1/billing/webhook/stripe` | Signature (`Stripe-Signature`) | raw body | `{...}` service result | 400 bad signature; **200** on duplicate/transient (never 5xx) |
| POST | `/api/v1/billing/webhook/creem` | Signature (`creem-signature`) | raw body | service result | 400 bad signature; 200 otherwise |
| POST | `/api/v1/billing/webhook/polar` | Signature (`webhook-id`/`-timestamp`/`-signature`) | raw body | service result | 400 bad signature/stale; 200 otherwise |
| POST | `/api/v1/billing/webhook/iyzico` | `token` exchange (form/query/JSON) | `token` field | service result | 400 missing token; 200 otherwise |
`plan_key` ∈ `starter`/`pro` (free is a signup grant). A `workspace_id` funds the
workspace SHARED pool and requires the caller to be workspace **admin+** (gate
runs before the provider session is created). Credits are granted **only** on
webhook confirmation. Webhooks never return 5xx on the duplicate/happy path —
idempotency + ledger provenance make a provider retry safe; only a bad signature
is non-2xx.
### 4.4 Me / Growth — `app/controllers/v1/me.py`
Per-user growth surfaces: insights, referrals, saved presets (with workspace
sharing). Router: `new_router()` (per-user).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| GET | `/api/v1/me/insights` | Per-user | — | dashboard analytics (caller-scoped) | 502 compute; 503 |
| GET | `/api/v1/me/referral` | Per-user | — | referral code + lifetime stats | 502; 503 |
| POST | `/api/v1/me/referral/redeem` | Per-user | `RedeemRequest` `{code}` | redemption result `{ok, referrer_*, referee_*}` | 400 no/invalid/self code; 409 already redeemed; 502; 503 |
| GET | `/api/v1/me/presets` | Per-user | — | own + workspace-shared presets `[{id, name, config, workspace_id, shared, created_at}]` | 401; 503 |
| POST | `/api/v1/me/presets` | Per-user | `PresetCreateBody` `{name, config, workspace_id?}` | preset descriptor | 400 no name/bad config; 403 not workspace member; 502; 503 |
| DELETE | `/api/v1/me/presets/{preset_id}` | Per-user | — | `{deleted: true, id}` | 403 shared, member-not-admin; 404 unknown/foreign private; 503 |
Preset deletion: a **personal** preset is creator-only (foreign → 404); a
**workspace-shared** preset is deletable by its creator OR a workspace `admin+`
(a plain member → 403, a non-member → 404, no existence leak).
### 4.5 Workspaces — `app/controllers/v1/workspaces.py`
Multi-seat membership + shared credit pool. Router: `new_router()` (per-user via
`_resolve_user`; all authorization delegated to `app/services/workspaces`).
Roles: `owner | admin | member`. Service exceptions map: `PermissionError`→403,
`ValueError`→400, duplicate-member invite→409, unknown workspace→404 (resolved
up front so a non-member of a real workspace gets 403, not a leak).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/workspaces` | Per-user | `WorkspaceCreateRequest` `{name}` | workspace `{id, name, owner_id, role, created_at}` | 400 blank name; 503 |
| GET | `/api/v1/me/workspaces` | Per-user | — | list of workspaces (+ caller role each) | 503 |
| GET | `/api/v1/workspaces/{id}/members` | Per-user (member) | — | roster `[{user_id, email, role, created_at}]` | 403 non-member; 404 unknown; 503 |
| POST | `/api/v1/workspaces/{id}/invite` | Per-user (admin+) | `InviteRequest` `{email, role?}` | member descriptor | 400 unknown email/invalid role; 403 under-privileged; 404 unknown ws; 409 already member; 503 |
| POST | `/api/v1/workspaces/{id}/members/{user_id}/role` | Per-user (admin+) | `RoleRequest` `{role}` | member descriptor | 400 invalid role; 403; 404; 503 |
| DELETE | `/api/v1/workspaces/{id}/members/{user_id}` | Per-user (admin+ or self) | — | `{removed: true}` | 403 (owner protected / under-privileged); 404; 503 |
| POST | `/api/v1/workspaces/{id}/leave` | Per-user (member) | — | `{left: true}` | 403 owner can't leave; 404; 503 |
| GET | `/api/v1/workspaces/{id}/credits` | Per-user (member) | — | `{balance: int}` (SHARED pool) | 403 non-member; 404; 503 |
| POST | `/api/v1/workspaces/{id}/credits/grant` | Per-user (admin+) | `WorkspaceGrantRequest` `{amount, reason?}` | `{balance: int}` (updated) | 400 non-positive amount; 403 non-admin; 404; 503 |
### 4.6 Schedule — `app/controllers/v1/schedule.py`
Queue a finished reel to auto-publish later (a Celery-beat due-runner publishes).
Router: `new_router()` (per-user). Platforms:
`scheduler.ALLOWED_PLATFORMS` (`tiktok`|`instagram`|`youtube_shorts`).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/jobs/{job_id}/schedule` | Per-user (owner) | `ScheduleRequest` `{platforms, scheduled_at (ISO-8601 UTC), youtube_privacy_status?}` | schedule row `{id, job_id, platforms, scheduled_at, status, ...}` | 400 no/unknown platforms, unparseable/past `scheduled_at`; 404 unknown/foreign job; 409 job not complete; 502; 503 |
| GET | `/api/v1/me/scheduled` | Per-user | query `status?` | list of schedules (soonest-due first) | 502; 503 |
| DELETE | `/api/v1/me/scheduled/{schedule_id}` | Per-user (owner) | — | `{id, status: "canceled"}` | 404 unknown/foreign; 409 not pending / lost race to runner; 502; 503 |
### 4.7 Covers — `app/controllers/v1/covers.py`
Render a 1080×1920 JPG cover/thumbnail for a reel. Router: `new_router()`
(per-user). One key per job (`jobs/{job_id}/cover.jpg`), regenerable.
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/jobs/{job_id}/cover` | Per-user (owner) | `CoverRequest` `{headline?, style?}` | `{cover_key, cover_url, style}` | 400 unknown style; 404 unknown/foreign job; 422 headline >180 chars; 502 render/upload/persist; 503 |
Headline priority: supplied `headline` → job's script hook (first non-empty line)
→ `params.video_subject`. Background: job `poster_key` (degrades to a style
gradient on download failure). Styles come from `GET /catalog/cover-styles`.
### 4.8 Voices — `app/controllers/v1/voices.py`
ElevenLabs Instant Voice Clone from an uploaded sample. Router: `new_router()`
(per-user).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/voices/clone` | Per-user | `CloneVoiceRequest` `{name, sample_key, consent, description?}` | `{id, voice_id ("elevenlabs:<id>"), name, status}` | 400 `consent` not true / no name / no sample_key / invalid sample; 403 sample not owned; 429 provider quota; 502 clone/persist; 503 service/asset model |
| GET | `/api/v1/voices/mine` | Per-user | — | caller's cloned voices `[{id, voice_id, name, status, created_at}]` | 401; 503 |
| DELETE | `/api/v1/voices/mine/{voice_id}` | Per-user (owner) | — | `{id, deleted: true}` | 404 unknown/foreign; 502 persist; 503 |
`consent === true` is mandatory (checked before any provider/storage work). The
returned `voice_id` (`elevenlabs:<provider_voice_id>`) is usable as a job
`voice_name`. Delete also best-effort removes the voice from ElevenLabs.
### 4.9 Brand — `app/controllers/v1/brand.py`
Per-user watermark/logo overlay settings (a `UserBrand` singleton). Router:
`new_router()` (per-user). Positions: `bottom_right`|`bottom_left`|`top_right`|
`top_left`; opacity `[0.0, 1.0]`.
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| GET | `/api/v1/me/brand` | Per-user | — | `{logo_key, position, opacity, enabled, logo_url?, updated_at}` (defaults when unset) | 401; 503 |
| PUT | `/api/v1/me/brand` | Per-user | `BrandRequest` `{logo_key?, position?, opacity?, enabled?}` | updated brand settings | 400 bad position/opacity; 403 logo not owned; 502 persist; 503 |
Omitted (`None`) fields leave stored values untouched; `logo_key=""` clears the
logo. A non-empty `logo_key` must reference an upload the caller owns (403).
### 4.10 Ideas (SPARK) — `app/controllers/v1/ideas.py`
AI idea engine: generate + save UGC video concepts. Router: `new_router()`
(per-user). Generation rate limit: `reelforge_ideas_rate_limit`/`_window_s`
(default 20/hour); save: `reelforge_save_idea_rate_limit`/`_window_s`
(default 60/hour).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/ideas/generate` | Per-user | `GenerateIdeasRequest` `{app_context, audience?, count? (1-10), language?}` | list of concepts | 400 empty `app_context`; 429 rate; 502 generation failed/empty; 503 |
| POST | `/api/v1/me/ideas` | Per-user | `SaveIdeaRequest` `{idea: object}` | `{id}` | 400 missing/empty idea; 429 rate; 502; 503 |
| GET | `/api/v1/me/ideas` | Per-user | — | saved concepts `[{id, title, hook, idea, created_at}]` (≤100) | 401; 503 |
| DELETE | `/api/v1/me/ideas/{idea_id}` | Per-user (owner) | — | `{deleted: true, id}` | 404 unknown/foreign; 503 |
### 4.11 Notifications — `app/controllers/v1/notifications.py`
In-app notification bell + center. Router: `new_router()` (per-user, strictly
owner-scoped via `NotificationRepository`). List page size:
`reelforge_notifications_limit` (default 50, max 200).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| GET | `/api/v1/me/notifications` | Per-user | query `unread_only` (bool), `limit?` | `{notifications: [{id, kind, title, body, data, read, created_at}], unread_count}` | 401; 503 |
| GET | `/api/v1/me/notifications/unread_count` | Per-user | — | `{unread_count}` | 401; 503 |
| POST | `/api/v1/me/notifications/{notification_id}/read` | Per-user (owner) | — | `{id, read: true}` | 404 unknown/foreign; 503 |
| POST | `/api/v1/me/notifications/read_all` | Per-user | — | `{updated: int, unread_count: 0}` | 401; 503 |
`unread_count` is always the caller's total (independent of page/filter). Marking
an already-read notification is an idempotent success.
### 4.12 Catalog — `app/controllers/v1/catalog.py`
Read-only reference lists for the creation wizard. Router: `new_router()`.
**Intentionally unauthenticated** (no per-user data, no DB access). Every handler
degrades to an empty list on failure (never 500).
| Method | Path | Auth | Success `data` |
|---|---|---|---|
| GET | `/api/v1/catalog/caption-styles` | None | `[{id, name, description, colours...}]` |
| GET | `/api/v1/catalog/music` | None | `[{id, name, filename, duration?}]` |
| GET | `/api/v1/catalog/music-generators` | None | enabled AI-BGM providers `[{id, name, max_prompt_length}]` |
| GET | `/api/v1/catalog/layouts` | None | `[{id, name, description}]` (`pip`/`hook_intro`/`split`) |
| GET | `/api/v1/catalog/templates` | None | curated job templates |
| GET | `/api/v1/catalog/dub-languages` | None | `[{code, name}]` |
| GET | `/api/v1/catalog/cover-styles` | None | `[{id, name}]` |
| GET | `/api/v1/catalog/social-platforms` | None | `[{id, name}]` (`tiktok`/`instagram`/`youtube_shorts`) |
| GET | `/api/v1/catalog/hooks` | None | `{<lang>: [hook, ...]}` |
### 4.13 Social — `app/controllers/v1/social.py`
AI social caption + hashtags for a reel. Router: `new_router()` (per-user via the
shared jobs resolver). Rate limit: `reelforge_social_rate_limit`/`_window_s`
(default 30/hour).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/jobs/{job_id}/social` | Per-user (owner) | `SocialRequest` `{platform, language?}` | `{title, caption, hashtags: [str]}` | 400 unsupported platform; 404 unknown/foreign job; 429 rate; 502 generation; 503 |
`platform` ∈ `tiktok`/`instagram`/`youtube_shorts` (`instagram`→LLM
`instagram_reels`). Subject/script come from the **job's own** persisted data,
never client input; a client `language` overrides the job's configured language.
### 4.14 LLM (legacy MPT) — `app/controllers/v1/llm.py`
Raw script/term/metadata generation. Router:
`new_router(dependencies=[Depends(base.verify_token)])` — gated by the **global**
`x-api-key` (§2.1), not per-user, because each call spends the operator's
Anthropic quota.
| Method | Path | Auth | Request | Success `data` |
|---|---|---|---|---|
| POST | `/api/v1/scripts` | `x-api-key` (global) | `VideoScriptRequest` | `{video_script}` |
| POST | `/api/v1/terms` | `x-api-key` (global) | `VideoTermsRequest` | `{video_terms}` |
| POST | `/api/v1/social-metadata` | `x-api-key` (global) | `VideoSocialMetadataRequest` | social metadata `{title, caption, hashtags, ...}` |
Auth failure → **401** `invalid token`.
### 4.15 Video (legacy MPT) — `app/controllers/v1/video.py`
The upstream MoneyPrinterTurbo controller, retained but **not** part of the
ReelForge job pipeline. Router: `new_router()` — the `verify_token` dependency is
**commented out**, so these are effectively open (guarded only by input
validation / path-traversal checks). Uses the in-memory or Redis task manager,
not the DB/Celery pipeline.
| Method | Path | Auth | Request | Notes |
|---|---|---|---|---|
| POST | `/api/v1/videos` | None | `TaskVideoRequest` | create task (stop_at=`video`); 429 queue full; 400 |
| POST | `/api/v1/subtitle` | None | `SubtitleRequest` | create task (stop_at=`subtitle`) |
| POST | `/api/v1/audio` | None | `AudioRequest` | create task (stop_at=`audio`) |
| GET | `/api/v1/tasks` | None | query `page`, `page_size` | `{tasks, total, page, page_size}` |
| GET | `/api/v1/tasks/{task_id}` | None | — | task status; 404 unknown |
| DELETE | `/api/v1/tasks/{task_id}` | None | — | delete task; 409 busy; 404 |
| GET | `/api/v1/musics` | None | — | local BGM files `{files: [{name, size, file}]}` |
| POST | `/api/v1/musics` | None | multipart `file` | upload BGM (≤30 MB, audio only); 400/500 |
| GET | `/api/v1/video_materials` | None | — | local material files |
| POST | `/api/v1/video_materials` | None | multipart `file` | upload material (video/image); 400 |
| GET | `/api/v1/stream/{file_path}` | None | `Range` header | 206 partial stream; 416 bad range |
| GET | `/api/v1/download/{file_path}` | None | — | file download (attachment) |
### 4.16 Public API keys — `app/controllers/v1/api_keys.py`
Per-user programmatic access: mint, list, inspect usage and revoke personal
`x-api-key` credentials. Router: `new_router()` (per-user). A minted key is
resolved back to its owner by `base.resolve_user_by_api_key` (§2.2) and carries
optional per-key `rate_limit_per_min` / `monthly_quota` limits (breach → **429**;
usage counted in the `api_key_usage` table). Active-key cap per user:
`reelforge_max_api_keys` (default 20).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/me/api-keys` | Per-user | `ApiKeyCreateRequest` `{name}` | `{id, name, key, prefix, created_at}` — **`key` (raw secret) is revealed exactly once** | 400 blank name; 409 active-key cap reached; 503 |
| GET | `/api/v1/me/api-keys` | Per-user | — | `[{id, name, prefix, last_used_at, revoked, created_at, rate_limit_per_min, monthly_quota, usage_this_month}]` (never the raw key/hash) | 401; 503 |
| GET | `/api/v1/me/api-keys/usage` | Per-user | — | per-key current-month usage `[{id, name, prefix, period_ym, used, rate_limit_per_min, monthly_quota, remaining}]` (`remaining=null` for an unlimited key) | 401; 503 |
| DELETE | `/api/v1/me/api-keys/{key_id}` | Per-user (owner) | — | `{id, revoked: true}` | 404 unknown/foreign (double-revoke is a 404 no-op); 503 |
The raw key (`rf_<token_urlsafe(32)>`) is generated server-side; only its
SHA-256 digest and a short non-secret `prefix` are stored, so the secret is
unrecoverable after the one-time reveal. Revoked keys can no longer authenticate.
### 4.17 Creator Analytics — `app/controllers/v1/analytics.py`
Per-user BI dashboard computed over the data ReelForge already records
(`Job`/`JobEvent`/`CreditLedger`) by `app/services/analytics`. Router:
`new_router()` (per-user, strictly caller-scoped — no path reads another user's
data).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| GET | `/api/v1/me/analytics` | Per-user | query `days` (1-365, def 30, clamped) | funnel, cost-over-time, credit burn-rate + live balance, render-time distribution, usage breakdowns, `+ {top_content}` (most-used templates/hooks, ≤10) | 502 compute; 503 |
### 4.18 Template Marketplace — `app/controllers/v1/marketplace.py`
Publish an immutable snapshot of a private template to a shared PUBLIC
marketplace; browse/search, view detail + remix lineage, clone, and rate it.
Router: `new_router()` (per-user — public *content* but still authed like every
other `/v1` route). Write rate limit (publish/clone/rate):
`reelforge_marketplace_rate_limit`/`_window_s` (default 120/hour per user).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| GET | `/api/v1/marketplace` | Per-user (auth gate) | query `query?`, `tag?`, `language?`, `sort` (`top`\|`new`\|`clones`\|`proven`\|`most_remixed`, def `top`), `limit` (1-100, def 20), `offset` | `[listing]` (see below); `sort=proven` re-ranks by real-world **win-score** and annotates each eligible listing with `win_score` (k-anonymity floor `WIN_SCORE_PUBLIC_MIN_COHORT` — absent for small cohorts) | 401; 503 |
| GET | `/api/v1/marketplace/{template_id}` | Per-user (auth gate) | — | one `listing` | 401; 404 unknown/unpublished; 503 |
| GET | `/api/v1/marketplace/{template_id}/lineage` | Per-user (auth gate) | — | `{ancestors: [listing], children: [listing]}` (remix tree — parents up the `parent_template_id` chain to root; direct still-published children) | 401; 503 |
| POST | `/api/v1/marketplace/publish` | Per-user (owner) | `PublishTemplateRequest` `{template_id?, title?, description?, prompt?, params?, tags?, language?, layout?}` | published `listing` (immutable COPY) | 400 empty resolved title; 404 foreign/missing referenced template; 429 rate; 502; 503 |
| POST | `/api/v1/marketplace/{template_id}/clone` | Per-user | — | `{id, name, source_marketplace_id}` (bumps `clone_count`) | 404 missing/unpublished; 429 rate; 502; 503 |
| POST | `/api/v1/marketplace/{template_id}/rate` | Per-user | `RateRequest` `{stars}` (1-5) | `listing` w/ fresh aggregate (one rating/user, upserted) | 400 stars out of `[1,5]`; 404 missing/unpublished; 429 rate; 502; 503 |
| DELETE | `/api/v1/marketplace/{template_id}` | Per-user (author-only) | — | `{unpublished: true, id}` (soft hide — clones/ratings survive) | 404 unknown/foreign/already-unpublished; 503 |
**`listing`** fields: `{id, author_user_id, title, description, prompt, params,
tags, language, layout, rating_avg, rating_count, clone_count, published,
created_at, updated_at, parent_template_id, remix_count, [win_score]}`.
`win_score` is attached **only** on the `sort=proven` browse.
### 4.19 Hook Performance Loop — `app/controllers/v1/performance.py`
Log the real-world outcome of a reel the caller posted, and read back the
aggregated deterministic "win score" the SPARK idea engine biases toward.
Router: `new_router()` (per-user, strictly owner-scoped). All list/ranking
`limit`s clamp to `[1, 100]`.
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/jobs/{job_id}/performance` | Per-user (owner) | `LogPerformanceRequest` `{platform?, views?, likes?, comments?, shares?, saves?, retention_pct?}` | logged metrics row (idempotent upsert; only supplied fields change) | 400 negative count / `retention_pct` outside `[0,100]`; 403 foreign job; 404 unknown job; 502; 503 |
| GET | `/api/v1/jobs/{job_id}/performance` | Per-user (owner) | — | the caller's metrics for that job | 404 unknown/foreign; 503 |
| GET | `/api/v1/me/performance` | Per-user | query `limit` (1-100, def 50), `offset` | caller's logged reels, newest first | 401; 503 |
| GET | `/api/v1/me/winning-hooks` | Per-user | query `limit` (1-100, def 10) | caller's top hooks by win score | 401; 503 |
| GET | `/api/v1/me/winning-templates` | Per-user | query `limit` (1-100, def 10) | caller's top templates by win score | 401; 503 |
Ownership is enforced in `app/services/hook_performance.log_performance` **before**
any write, so a guessed id can neither write to nor confirm another user's job.
### 4.20 Direct-Publish Account-Connect (OAuth) — `app/controllers/v1/connections.py`
Connect a social platform (TikTok / Instagram / YouTube) via the OAuth
authorization-code flow, then publish one of the caller's own completed jobs
straight to the connected account. Router: `new_router()` (per-user).
**Tokens are Fernet-encrypted at rest** (`social_accounts.access_token_enc` /
`refresh_token_enc`) using **`SOCIAL_TOKEN_KEY`** (required for any connection);
**no endpoint ever serialises a token** — every response is TOKEN-FREE. Connect
rate limit: `reelforge_connect_rate_limit`/`_window_s` (default 30/hour); publish:
`reelforge_direct_publish_rate_limit`/`_window_s` (default 60/hour).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| GET | `/api/v1/me/connections` | Per-user | — | `[{provider, external_account_id, connected, status (`connected`\|`expired`), scopes, token_expires_at, connected_at, updated_at}]` (TOKEN-FREE) | 401; 503 |
| GET | `/api/v1/connections/{provider}/authorize` | Per-user | query `scopes?` | `{provider, authorize_url, state}` (opaque single-use CSRF `state`) | 404 unknown provider; 429 rate; 503 provider/redirect not configured |
| GET | `/api/v1/connections/{provider}/callback` | Per-user | query `code`, `state` | caller's connection list (TOKEN-FREE) after exchange + encrypted store | 400 invalid/replayed `state` or missing `code`; 404 unknown provider; 502 store/crypto; 503 |
| DELETE | `/api/v1/me/connections/{provider}` | Per-user (owner) | — | `{disconnected: true, provider}` | 404 unknown provider / not connected; 503 |
| POST | `/api/v1/jobs/{job_id}/publish/{provider}` | Per-user (owner) | query `caption?` (≤2200) | `{provider, external_post_id, url, status: "published"}` | 404 unknown provider/job; 403 foreign job; 409 job not complete **or** provider not connected **or** reconnect required; 429 rate; 502 storage/publish; 503 publish not configured/wired |
`state` is consumed exactly once (single-use CSRF) **before** any code exchange.
The upload client is injected (no default live network client) — an unwired
deployment fails clean (**503**), never makes an unexpected outbound call.
### 4.21 Public Watermarked Share Pages — `app/controllers/v1/share.py`
Turn one of the caller's completed reels into a public, unguessable, revocable
share link; anyone (no auth) can view the resulting watermarked page. Router:
`new_router()`. Base URL: `reelforge_share_base_url` (empty → site-relative
`/r/<token>`). Write rate limit: `reelforge_share_write_rate_limit`/`_window_s`
(default 120/hour per user); public-view rate limit (per-IP):
`reelforge_share_view_rate_limit`/`_window_s` (default 600/hour).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| POST | `/api/v1/jobs/{job_id}/share` | Per-user (owner) | — | `{token, url, job_id, view_count, revoked, created_at}` (idempotent — one live link/job) | 404 unknown/foreign job; 429 rate; 502; 503 |
| DELETE | `/api/v1/me/shares/{token}` | Per-user (owner) | — | `{revoked: bool, token}` (idempotent — a foreign/unknown/already-revoked token is a harmless `{revoked: false}`, never a 404 that confirms existence) | 401; 503 |
| GET | `/api/v1/public/r/{token}` | **None (PUBLIC)** | — | SAFE public DTO `{title, watermarked preview url, created_at, sharer referral code}` (counts a view) | 404 unknown/revoked token; 429 rate; 502; 503 |
The public route deliberately never calls `_resolve_user`; the strict
`SharePublicModel` response contract guarantees no clean `result_key`, owning
`user_id` or private financial can leak.
### 4.22 Creator Profiles + Follow Graph + Leaderboards — `app/controllers/v1/creators.py`
Public creator identity, a directed follow graph and a deterministic reputation
leaderboard. Router: `new_router()`. The leaderboard + profile reads are PUBLIC
(skip `_resolve_user`); follow/unfollow/following/profile-edit are per-user.
Follow rate limit: `reelforge_follow_rate_limit`/`_window_s` (default 300/hour).
| Method | Path | Auth | Request | Success `data` | Errors |
|---|---|---|---|---|---|
| GET | `/api/v1/creators/leaderboard` | **None (PUBLIC)** | query `metric` (`reputation` def \| `followers` \| `clones` \| `rating` \| `published` \| `win_score`), `limit` (1-100, def 20) | ranked creators (safe fields + score + rank + `user_id`/`handle`) | 503 |
| GET | `/api/v1/creators/{handle_or_id}` | **None (PUBLIC)** | — | SAFE public profile (by id OR handle; never credits/email/cost/revenue) | 400 blank id; 404 unknown; 503 |
| POST | `/api/v1/creators/{creator_id}/follow` | Per-user | — | follow state (idempotent) | 400 self-follow/blank id; 404 unknown followee; 429 rate; 503 |
| DELETE | `/api/v1/creators/{creator_id}/follow` | Per-user | — | `{removed: bool}` (idempotent no-op) | 400 blank id; 503 |
| GET | `/api/v1/me/following` | Per-user | — | SAFE public profiles the caller follows (≤100, newest edge first) | 401; 503 |
| PATCH | `/api/v1/me/profile` | Per-user | `ProfileUpdateRequest` `{handle?, display_name?, bio?}` | caller's updated SAFE public profile | 409 handle already taken; 502; 503 |
Route order matters: `/creators/leaderboard` is registered **before**
`/creators/{handle_or_id}` so `leaderboard` is never captured as a handle.
---
## 5. Health & non-versioned routes
| Method | Path | Auth | Response |
|---|---|---|---|
| GET | `/ping` | None | `"pong"` (plain string) |
| GET | `/tasks/*` | None | static legacy task artifacts |
| GET | `/*` | None | static public SPA |
---
## 6. HTTP status code summary
| Code | Meaning in this API |
|---|---|
| 200 | Success (also the ack for duplicate/transient payment webhooks) |
| 400 | Controller-level validation failure (bad/empty field, unknown enum, past timestamp) |
| 401 | Auth failure (bad `x-api-key`, missing header, invalid Clerk bearer) |
| 402 | Insufficient credits (personal or workspace pool) |
| 403 | Authorization / ownership failure (foreign R2 key, non-member/under-privileged workspace action) |
| 404 | Unknown or foreign resource (job/batch/schedule/preset/voice/notification/idea/workspace/api-key/template/connection/share-token/creator/provider) — no existence leak |
| 409 | State conflict (job not complete/retryable, already published, duplicate member, no longer pending, active-key cap reached, provider not connected / reconnect required, handle already taken) |
| 416 | Invalid HTTP `Range` (legacy `/stream`) |
| 422 | Pydantic request-body schema violation (framework default) |
| 429 | Rate limit exceeded, task queue full, provider quota, or personal-API-key rate-limit / monthly-quota breach |
| 502 | Downstream/provider failure (R2, payment provider, LLM, HeyGen, publish) |
| 503 | A required persistence/service layer is unavailable (import-safe degradation) |