# REST API — LLM Integration Guide

You are an autonomous agent that has been given a **base URL** and an **API key** for the service documented below. This document is self-contained: it tells you everything needed to call the API. Follow it literally.

- **Base URL:** `https://api.test.podcastor.eu`
- **API key:** provided to you separately; it starts with `sk_`.
- **All paths below are relative to the base URL** (e.g. `https://api.test.podcastor.eu/api/v1/health`).

> Generated from the app's single source of truth. If an endpoint
> behaves differently from what you read here, trust the live response
> and report the mismatch — the docs are meant to be authoritative.

## Essentials

### Base URL

All endpoints live under `https://api.test.podcastor.eu/api/v1`. `https://api.test.podcastor.eu` is the origin you were given (scheme + host, e.g. `https://example.com`). Do not add a trailing slash.

### Authentication

Every endpoint requires an API key sent as a Bearer token:
`Authorization: Bearer sk_your_key_here`. Keys always start with `sk_`. A missing or invalid key returns `401 { "error": "Invalid or missing API key" }`. Create keys in the app under Profile → API Keys.

### Content type

Responses are JSON unless noted (file download returns raw bytes). Request bodies are JSON (`Content-Type: application/json`) except file upload, which is `multipart/form-data`.

### Rate limiting

Requests are rate limited per API key. When you exceed a limit you get `429` (or `403` if the limit is configured to block) with an `error` message and, when applicable, a `Retry-After` header (seconds). Back off and retry.

### Errors

Errors are JSON with an `error` string and a matching HTTP status (`400` bad input, `401` unauthenticated, `403` forbidden, `404` not found, `413` payload too large, `429` rate limited, `500` server error).

## Quick start

```bash
# 1. Verify your key works
curl https://api.test.podcastor.eu/api/v1/health -H "Authorization: Bearer sk_your_key_here"
# A 200 with {"status":"healthy",...} means you are authenticated.
```

## Endpoints

### GET /api/v1/health

**Health check** — Confirms the API is up and your key is valid. Handy as a first call to verify credentials and connectivity.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key.

**Request**

```bash
curl https://api.test.podcastor.eu/api/v1/health \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "status": "healthy",
  "timestamp": "2026-07-19T12:00:00.000Z",
  "uptime": 1234.56,
  "version": "1.0.0",
  "apiKey": "My key",
  "userId": "usr_...",
  "message": "API is running successfully"
}
```

---

### GET /api/v1/stats

**Account & API usage stats** — Returns the calling user together with API-usage counters (requests today / this week / this month, error rate, API-key count).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key (scoped to the key owner).

**Request**

```bash
curl https://api.test.podcastor.eu/api/v1/stats \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "user": { "id": "usr_...", "email": "you@example.com", "name": "You", "role": "user", "createdAt": "..." },
  "apiStats": {
    "totalApiKeys": 2,
    "requestsToday": 14,
    "requestsThisWeek": 98,
    "requestsThisMonth": 412,
    "errorRate": "1.20%",
    "errorCount": 5
  },
  "meta": { "timestamp": "...", "apiKey": "My key" }
}
```

---

### GET /api/v1/stats/shows/:id

**Show download report (IAB v2.2)** — Download statistics of one show, counted with IAB v2.2-style rules (one download per listener — hashed IP + User-Agent — per episode per rolling 24 h, at least one minute of audio delivered, probes and bots removed, edge-cache hits merged in). Returns totals, downloads per day, per-episode day-1/7/30/90 benchmarks with the show median, apps, countries, regions, devices, OS, referrers of web plays and YouTube views. With `format=csv` one table is returned as CSV. Also served at `https://api.<base>/v1/stats/shows/:id`.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** A key whose owner is a member of the show’s workspace (others get 404).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Show id (from the studio URL /app/shows/:id). |
| `days` | query | integer | no | Window, 1–3650 days (default 30); clamped to the plan’s analytics history (`clamped: true`). |
| `format` | query | string | no | `csv` for a CSV download instead of JSON. |
| `table` | query | string | no | With format=csv: episodes (default) \| days \| apps \| countries \| regions \| devices \| os \| referrers. |

**Request**

```bash
curl "https://api.test.podcastor.eu/api/v1/stats/shows/shw_123?days=90" \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "show": { "id": "shw_123", "slug": "myshow", "title": "My Show" },
  "days": 90, "clamped": false,
  "source": "merged",
  "total": 1840,
  "perDay": [{ "day": "2026-12-01", "downloads": 31 }],
  "perEpisode": [{ "episodeId": "ep_1", "title": "Episode 1", "downloads": 412 }],
  "episodes": [{ "episodeId": "ep_1", "title": "Episode 1", "publishedAt": "2026-10-01T06:00:00.000Z", "total": 530, "downloads": 412, "d1": 120, "d7": 290, "d30": 450, "d90": null, "youtubeViews": 88 }],
  "medians": { "d1": 110, "d7": 270, "d30": 400, "d90": null },
  "apps": [{ "name": "Apple Podcasts", "downloads": 900 }],
  "countries": [{ "name": "DE", "downloads": 700 }],
  "regions": [{ "name": "DE · BE", "downloads": 120 }],
  "devices": [{ "name": "mobile", "downloads": 1500 }],
  "os": [{ "name": "iOS", "downloads": 1000 }],
  "referrers": [{ "name": "myshow.com", "downloads": 40 }],
  "youtube": { "connected": true, "totalViews": 312 },
  "edgeRequests": []
}
```

> `d1`…`d90` are null while an episode is younger than that many days.
>
> `source`: `origin` (counted at the origin), `merged` (raw edge logs + origin, deduplicated) or `edge-logs` (only aggregated edge request counts available — see `edgeRequests`).
>
> Responses are `Cache-Control: no-store`.

---

### GET /api/v1/users

**List users** — Lists users. A regular key returns only its own user record; an admin key returns all users with pagination.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key (admin keys see all users; others see themselves).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `limit` | query | integer | no | Page size, 1–100 (default 10). Admin only; ignored for non-admins. |
| `offset` | query | integer | no | Rows to skip (default 0). Admin only. |

**Request**

```bash
curl "https://api.test.podcastor.eu/api/v1/users?limit=20&offset=0" \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "users": [
    { "id": "usr_...", "email": "you@example.com", "name": "You", "role": "user", "emailVerified": null, "createdAt": "..." }
  ],
  "meta": { "limit": 20, "offset": 0, "total": 1, "apiKey": "My key" }
}
```

---

### POST /api/v1/users

**Create user (scaffold)** — Admin-only endpoint scaffold for creating a user. Ships as a stub in this starter — it validates input and echoes it back rather than persisting. Fill in real creation logic before relying on it.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Admin API keys only (others get 403).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `email` | body | string | yes | New user email. |
| `name` | body | string | yes | New user display name. |
| `role` | body | string | no | 'user' (default) or 'admin'. |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/v1/users \
  -H "Authorization: Bearer sk_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"email":"new@example.com","name":"New User","role":"user"}'
```

**Response**

```
{
  "message": "User creation endpoint - implementation needed",
  "requestedData": { "email": "new@example.com", "name": "New User", "role": "user" },
  "apiKey": "My key"
}
```

> This is a template stub — no user is actually created yet.

---

### POST /api/v1/files

**Upload a file** — Uploads a file and stores its raw bytes. Use this instead of a form/Server Action for any real upload (Server Actions cap the body at ~1MB; this endpoint does not). Send `multipart/form-data` with a single `file` field.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key (the file is owned by the key owner).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `file` | form | file | yes | The file to upload (multipart field name must be "file"). |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/v1/files \
  -H "Authorization: Bearer sk_your_key_here" \
  -F "file=@./photo.png"
```

**Response**

```
{
  "id": "fil_...",
  "filename": "photo.png",
  "url": "/api/v1/files/fil_..."
}
```

> Default max size is 100MB (configurable via MAX_FILE_SIZE). Oversized uploads return 413.
>
> The returned `url` is the Bearer-gated download endpoint below.

---

### GET /api/v1/files/:id

**Download / preview a file** — Streams the raw file bytes with the stored Content-Type. Because it is Bearer-gated you cannot put it directly in an `<img src>`; fetch it with the token and build an object URL client-side.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | File id returned by the upload endpoint. |

**Request**

```bash
curl https://api.test.podcastor.eu/api/v1/files/fil_your_file_id \
  -H "Authorization: Bearer sk_your_key_here" \
  --output downloaded-file
```

**Response**

```
Raw binary body with the stored `Content-Type` and `Content-Disposition: inline; filename="..."`. Returns `404 { "error": "File not found" }` if unknown.
```

---

### DELETE /api/v1/files/:id

**Delete a file** — Deletes a file owned by the calling key.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key (only the owner may delete).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | File id to delete. |

**Request**

```bash
curl -X DELETE https://api.test.podcastor.eu/api/v1/files/fil_your_file_id \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{ "deleted": true }   // { "deleted": false } with status 404 if not found / not owned
```

---

### POST /api/media/uploads

**Start a resumable media upload** — Creates a media item and an upload. Then PUT each part (8 MiB, any order, retry freely) and POST …/complete. Bytes are encrypted (PCM1) and stored on sharefiles.eu; the session cookie or an `sk_` key works. Acts on your active workspace — pass `?workspaceId=` or `X-Workspace-Id` to pick another one you belong to.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above. Size limit 4 GB/file by default (413 above).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `name` | body | string | yes | Original file name (display only; never used in storage paths). |
| `size` | body | integer | yes | Exact size in bytes. |
| `type` | body | string | no | MIME type (else inferred from the name). |
| `openEnded` | body | boolean | no | Size unknown up front (live recordings): omit `size`; parts may be any length up to `partSize`; `complete` takes the final `size`. |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/media/uploads \
  -H "Authorization: Bearer sk_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"name":"episode-1.wav","size":115200044,"type":"audio/wav"}'
```

**Response**

```
{ "uploadId": "up_…", "mediaId": "med_…", "partSize": 8388608, "partCount": 14, "kind": "audio", "contentType": "audio/wav" }
```

---

### PUT /api/media/uploads/:id/parts/:n

**Upload one part** — Raw request body (not multipart) of exactly `partSize` bytes — the last part carries the remainder. Parts are numbered from 0, may arrive in any order and re-sending one is safe.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | uploadId. |
| `n` | path | integer | yes | Part number 0 … partCount-1. |

**Request**

```bash
dd if=episode-1.wav bs=8388608 skip=0 count=1 2>/dev/null | \
curl -X PUT https://api.test.podcastor.eu/api/media/uploads/up_…/parts/0 -H "Authorization: Bearer sk_your_key_here" --data-binary @-
```

**Response**

```
{ "part": 0, "size": 8388608 }
```

> Open-ended uploads: any part may be shorter than `partSize` (send `Content-Length`), but the parts concatenated in order must total the `size` given to `complete`.
>
> `507` when the server-side spool is full — retry later.
>
> `GET /api/media/uploads/:id` lists `receivedParts` to resume after a crash; `DELETE` aborts.

---

### POST /api/media/uploads/:id/complete

**Complete an upload** — Checks that every part is present, then returns 202 at once. The parts are streamed through encryption into storage in the background, then previews/peaks/posters (ConvertHippo) start. Follow `GET /api/media/:id` (or SSE `GET /api/media/:id/events`) until `stored` is true (`status` then moves on to `ready`) or `status` is `failed` (call complete again to retry).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | uploadId. |
| `size` | body | integer | no | Open-ended uploads only: the final total size in bytes (sets the part count). |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/media/uploads/up_…/complete -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
202 { "mediaId": "med_…", "uploadId": "up_…", "status": "processing", "accepted": true }
```

> `409 { "missingParts": [3, 7] }` when parts are absent — send them and call complete again.
>
> Idempotent: while storing it returns the same 202; once stored, 200 with the media `status` and `accepted: false`.
>
> No request may run past the 30 s edge cutoff, so big files are never stored inside this request.

---

### POST /api/media/import

**Import media from a public URL** — Server-side streamed fetch of a public http(s) URL, in the background: returns 202 at once. Follow `GET /api/media/:id` (or `/events`) until `stored` or `failed` (reason in `statusMessage`). Private/internal addresses are refused (checked on every redirect); the size limit applies.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `url` | body | string | yes | Public http(s) URL. |
| `name` | body | string | no | Display name (default: from the URL). |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/media/import -H "Authorization: Bearer sk_your_key_here" \
  -H "Content-Type: application/json" -d '{"url":"https://example.com/talk.mp3"}'
```

**Response**

```
202 { "mediaId": "med_…", "status": "processing", "accepted": true }
```

---

### GET /api/media

**List the media library** — Media of the workspace, newest first, with derivative roles (peaks, preview, proxy, poster, thumbnail…) and service status.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any workspace member.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `kind` | query | string | no | audio \| video \| image \| subtitle \| project-export \| other |

**Request**

```bash
curl https://api.test.podcastor.eu/api/media -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{ "workspaceId": "…", "role": "owner", "media": [ { "id": "med_…", "kind": "audio", "name": "episode-1.wav", "size": 115200044, "durationMs": 600000, "status": "ready", "derivatives": [ { "role": "preview", "size": 4800000, "contentType": "audio/ogg" } ] } ], "services": { "mediaStore": true, "converthippo": true } }
```

---

### PATCH /api/media/:id

**Rename media** — Changes the display name. `GET /api/media/:id` returns one item; `DELETE /api/media/:id` deletes it and every derivative from storage.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Rename/delete: workspace editor or above. Get: any member.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `name` | body | string | yes | New display name. |

**Request**

```bash
curl -X PATCH https://api.test.podcastor.eu/api/media/med_… -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"name":"Episode 1 (final)"}'
```

**Response**

```
{ "id": "med_…", "name": "Episode 1 (final)", … }
```

---

### DELETE /api/media/:id

**Delete media** — Hides the item at once; the original and all derivatives are removed from sharefiles in the background, then the rows.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Request**

```bash
curl -X DELETE https://api.test.podcastor.eu/api/media/med_… -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{ "deleted": true }
```

---

### GET /api/media/:id/events

**Follow a media item (SSE)** — Server-sent events of the media item (same shape as `GET /api/media/:id`): `event: media` on every change, `event: done` once `status` is `ready` or `failed`. The stream ends after ~20 s (`retry: 1000`); EventSource reconnects. Use it after `complete` / import (202) to see `stored` become true, or poll `GET /api/media/:id`.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any workspace member.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | mediaId. |

**Request**

```bash
curl -N https://api.test.podcastor.eu/api/media/med_…/events -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
event: media
data: { "id": "med_…", "status": "processing", "stored": false, … }

event: done
data: { "id": "med_…", "status": "ready", "stored": true, … }
```

---

### GET /api/media/:id/stream

**Stream / download media (Range supported)** — Decrypts on the fly. Supports `Range` (206 + Content-Range, 416), `HEAD`, `ETag` (plaintext sha256) and `If-None-Match`. Only the encrypted chunks covering the range are fetched, so seeking in multi-GB files is cheap.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any workspace member.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `role` | query | string | no | A derivative instead of the original: preview, playable, proxy, poster, thumbnail, peaks, analysis, pcm… `404 { code: "derivative_missing" }` when it does not exist (yet). |
| `d` | query | string | no | Alias of `role` (the audio editor reads `?d=pcm` windows by Range: byte offset = dataOffset + t·48000·channels·2, where dataOffset is where the WAV `data` chunk starts — 44 for a canonical header, more when a `LIST` chunk comes first). |
| `download` | query | 1 | no | Content-Disposition: attachment. |
| `Range` | header | string | no | e.g. `bytes=1048576-2097151`. |

**Request**

```bash
curl https://api.test.podcastor.eu/api/media/med_…/stream -H "Authorization: Bearer sk_your_key_here" -H "Range: bytes=0-1023" -o first-kib.bin
```

**Response**

```
Raw bytes: 200 (whole) or 206 (range).
```

---

### POST /api/media/:id/signed-url

**Short-lived signed URL** — Returns `/m/<token>` for `<audio>`/`<video>` elements or other tools that cannot send a Bearer header: HMAC-signed, valid 1 hour, GET/HEAD only, bound to this media (and derivative role). Range supported.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any workspace member.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `role` | body | string | no | Derivative role (default: the original). |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/media/med_…/signed-url -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"role":"preview"}'
```

**Response**

```
{ "url": "/m/eyJ…", "expiresAt": "2026-12-03T12:00:00.000Z" }
```

---

### POST /api/media/:id/pcm

**Make media editable (pcm + peaks)** — Ensures the `pcm` derivative (16-bit WAV, 48 kHz, made by ConvertHippo `audio.convert`) and `peaks` exist, starting the jobs if needed. Poll until `pcm` is true. Stop when `status` is `failed`: the pcm (or the step producing its input) failed after the server's retries (3 tries on 5xx/504/network errors) — `processingFailed` names the roles; retry with `POST /api/media/:id/reprocess`. Each job carries `timings` (ms epoch: createdAt, submittedAt, startedAt, finishedAt, storedAt, failures).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/media/med_…/pcm -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{ "pcm": false, "peaks": true, "status": "processing", "statusMessage": null, "processingFailed": null, "jobs": [ { "id": "pj_…", "role": "pcm", "status": "running", "progress": 35, "error": null, "message": null, "timings": { "createdAt": 1764763874000 } } ], "comingSoon": [] }
```

---

### POST /api/media/:id/reprocess

**Retry failed processing** — "Processing failed — retry": marks the media's failed (and canceled) derivative jobs superseded and plans its derivatives (preview, pcm, peaks…) again. Returns at once; follow progress with `POST /api/media/:id/pcm` or `GET /api/media/:id`, whose `processingFailed` is non-null while a derivative is failed.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/media/med_…/reprocess -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
202 { "retried": 1 }
```

---

### GET /api/audio-projects

**List audio projects** — Projects of the workspace, most recently edited first, with track/clip counts and length. `GET /api/audio-projects/:id` returns one with its `doc` and `revision`.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any workspace member.

**Request**

```bash
curl https://api.test.podcastor.eu/api/audio-projects -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{ "projects": [ { "id": "ap_…", "name": "Episode 12", "revision": 41, "updatedAt": "2026-12-03T10:00:00.000Z", "tracks": 2, "clips": 7, "duration": 3605.2 } ] }
```

---

### POST /api/audio-projects

**Create an audio project** — Either from a document (`{name, doc}`) or from media (`{mediaIds, oneTrack}` — one clip per media, end to end on track 1 when `oneTrack`). `409 { code: "processing" }` while a media item is still being prepared.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above. At most 1000 projects per workspace.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `name` | body | string | no | Display name. |
| `doc` | body | object | no | Project document (version 1: tracks, clips, markers; ≤ 2 MiB). Media ids must belong to the workspace. |
| `mediaIds` | body | string[] | no | Create from these media instead of a doc. |
| `oneTrack` | body | boolean | no | Put all media on one track. |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/audio-projects -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"mediaIds":["med_…"],"oneTrack":true}'
```

**Response**

```
{ "id": "ap_…", "name": "episode-1", "revision": 1, "doc": { "version": 1, "sampleRate": 48000, "channels": 2, "tracks": [ … ], "master": { "volume": 1, "filters": [] }, "markers": [] } }
```

---

### PUT /api/audio-projects/:id

**Save a project document** — Optimistic concurrency: send the revision you based the edit on. On success the revision increments. `PATCH` renames (`{name}`), `DELETE` deletes (the media stays in the Library).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `baseRevision` | body | integer | yes | The revision your doc is based on. |
| `doc` | body | object | yes | The whole document (≤ 2 MiB, else 413). |
| `saveId` | body | string | no | Optional client id of this save (8–64 of `A-Za-z0-9_-`). Retrying the same save with the same id after a lost response returns the saved project instead of 409. Returned as `lastSaveId`. |

**Request**

```bash
curl -X PUT https://api.test.podcastor.eu/api/audio-projects/ap_… -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"baseRevision":41,"doc":{…}}'
```

**Response**

```
{ "id": "ap_…", "name": "Episode 12", "revision": 42, "doc": { … }, "updatedAt": "…" }
```

> `409 { code: "conflict", project: { id, name, revision, lastSaveId, doc } }` when someone saved since `baseRevision` (if `lastSaveId` is one of your own save ids, that revision is yours — rebase on it) — reload, or keep yours with `POST /api/audio-projects/:id/duplicate {doc}`.

---

### POST /api/audio-projects/:id/duplicate

**Duplicate a project** — Copies the project (or saves the given `doc` as a copy — the editor's "keep mine").

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `doc` | body | object | no | Save this document as the copy instead of the stored one. |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/audio-projects/ap_…/duplicate -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{}'
```

**Response**

```
{ "id": "ap_…", "name": "Episode 12 (copy)", "revision": 1 }
```

---

### POST /api/audio-projects/:id/snapshots

**Save a named version** — Snapshots the current document. Hourly automatic snapshots are taken on save; the last 50 of each kind are kept. `GET` lists them; `POST …/snapshots/:sid/restore` restores one (as a new revision).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Save/restore: workspace editor or above. List: any member.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `name` | body | string | no | Version name. |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/audio-projects/ap_…/snapshots -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"name":"Before edit"}'
```

**Response**

```
{ "id": "aps_…" }   // GET: { "snapshots": [ { "id", "name", "kind": "named"|"auto", "revision", "createdAt" } ] }
```

---

### POST /api/audio-projects/:id/effects

**Apply a ConvertHippo filter to source ranges** — One job per distinct media runs the filter (its own catalog entry) on the WHOLE source media; options are validated against the entry's schema (`422 schema_mismatch` otherwise). Each output is a new media item (`derivedFrom` the source); the response marks each job `whole: true` and the editor repoints its clips with their offset unchanged.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above. `404 coming_soon` for filters not in the catalog.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `conversionId` | body | string | yes | A catalog entry of group `filter`. |
| `options` | body | object | no | Validated against the entry's schema. |
| `spans` | body | array | yes | `[{ mediaId, start, end }]` in source seconds (≤ 200). |
| `title` | body | string | no | Used in the new media names. |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/audio-projects/ap_…/effects -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"conversionId":"audio.denoise","spans":[{"mediaId":"med_…","start":0,"end":60}]}'
```

**Response**

```
{ "jobs": [ { "jobId": "pj_…", "mediaId": "med_…", "start": 0, "end": 60, "whole": false } ], "chained": true }
```

> `POST /api/audio-projects/:id/effects/preview {conversionId, options, mediaId, start, end}` (≤ 30 s) renders a `filtered:<hash>` derivative for A/B listening → `{ role, jobId|null }`.

---

### POST /api/audio-projects/:id/export

**Export (mix + encode) a project** — Writes timeline.json (ConvertHippo's published schema, validated before submitting — `422 schema_mismatch` otherwise) and runs ConvertHippo `audio.render-timeline`, with the markers as its `chapters` job option (returned as `chapters`); the result is a media item with source `render`. Without render-timeline, a one-track one-clip project goes through `audio.filter-chain`; otherwise `404 coming_soon`. `GET` returns the capabilities (formats, loudness, which recipes exist).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `format` | body | string | yes | mp3-128 \| mp3-192 \| mp3-320 \| m4a \| wav \| flac \| opus |
| `baseRevision` | body | integer | yes | Must equal the stored revision (`409 { code: "stale" }` otherwise). |
| `range` | body | object | no | `{ start, end\|null }` seconds; default the whole project. |
| `loudness` | body | number | no | Integrated loudness target in LUFS (e.g. −16), or null. |
| `chapters` | body | boolean | no | Write chapters from the project's markers (ID3 CHAP in mp3, MP4 chapters in m4a; sent as the `chapters` option of audio.render-timeline). |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/audio-projects/ap_…/export -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"format":"mp3-192","baseRevision":42,"loudness":-16,"chapters":true}'
```

**Response**

```
{ "jobId": "pj_…", "via": "audio.render-timeline" }
```

---

### GET /api/converthippo/catalog

**Processing catalog** — The live ConvertHippo catalog (cached 10 min) with each option JSON Schema pre-mapped to form `fields`, plus `comingSoon` ids this app wants but ConvertHippo does not offer yet. `?group=filter` = the Effects menu.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any signed-in user.

**Request**

```bash
curl "https://api.test.podcastor.eu/api/converthippo/catalog?group=filter" -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{ "configured": true, "conversions": [ { "id": "audio.convert", "group": "convert", "outputs": ["mp3","opus"], "options": { … }, "fields": [ { "key": "bitrate", "kind": "enum", … } ] } ], "comingSoon": ["audio.analyze"] }
```

---

### POST /api/jobs

**Run a conversion / effect** — Starts a ConvertHippo job on media of your workspace. Options are validated against the catalog schema. Outputs are stored as a new media item (default) or as a derivative (`target: {kind:"derivative", mediaId, role:"filtered:<hash>"|"render"}`).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above. `404 coming_soon` for conversions not in the catalog yet; `503 not_configured` without ConvertHippo.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `conversionId` | body | string | yes | Catalog id, e.g. `audio.convert`. |
| `inputs` | body | array | yes | `[{ "mediaId": "med_…", "role": "preview"? }]` |
| `options` | body | object | no | Must match the entry's JSON Schema. |
| `to` | body | string | no | Output format from the entry's `outputs`. |
| `target` | body | object | no | `{kind:"media", name?}` (default) or `{kind:"derivative", mediaId, role}`. |

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/jobs -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" \
  -d '{"conversionId":"audio.convert","to":"mp3","options":{"bitrate":"128k"},"inputs":[{"mediaId":"med_…"}]}'
```

**Response**

```
{ "id": "pj_…", "status": "pending", "progress": 0, "conversionId": "audio.convert", "chJobId": null, … }
```

---

### GET /api/jobs/:id/events

**Follow a job (SSE)** — Server-Sent Events: `event: job` with the full job row on every change, a final `event: done`. `GET /api/jobs/:id` returns the row; `GET /api/jobs` lists recent jobs.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any workspace member.

**Request**

```bash
curl -N https://api.test.podcastor.eu/api/jobs/pj_…/events -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
retry: 3000

event: job
data: {"id":"pj_…","status":"running","progress":40,…}

event: done
data: {"id":"pj_…","status":"succeeded","outputs":[{"mediaId":"med_…","size":4800000}],…}
```

---

### DELETE /api/jobs/:id

**Cancel a job** — Cancels a pending/running job (also on ConvertHippo when it has started there). Finished jobs are unchanged.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace editor or above.

**Request**

```bash
curl -X DELETE https://api.test.podcastor.eu/api/jobs/pj_… -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{ "id": "pj_…", "status": "canceled", … }
```

---

### GET /api/v1/shows/:slug

**Public show (no auth)** — A published show as JSON for websites that list a podcast themselves. Anonymous, CORS open (`Access-Control-Allow-Origin: *`), CDN-cached (`public, max-age=60, s-maxage=300`, purged on every change). On the api. host: `https://api.{base}/v1/shows/:slug`. Private shows answer 404.

- **Auth:** none
- **Access:** Anyone.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `slug` | path | string | yes | Show slug (its subdomain). |

**Request**

```bash
curl https://api.test.podcastor.eu/api/v1/shows/my-show
```

**Response**

```
{
  "show": {
    "slug": "my-show", "title": "My Show", "subtitle": null, "descriptionHtml": "<p>…</p>", "author": "Me",
    "language": "en", "categories": [{ "category": "Technology" }], "explicit": false, "type": "episodic",
    "artworkUrl": "https://media.podcastor.eu/e/k3v9q2mz7d-1/my-show-artwork.jpg",
    "siteUrl": "https://my-show.podcastor.eu/", "feedUrl": "https://feeds.podcastor.eu/my-show.xml",
    "videoFeedUrl": "https://feeds.podcastor.eu/my-show/video.xml", "embedUrl": "https://embed.podcastor.eu/show/my-show",
    "podcastGuid": "…", "directories": { "apple": "https://podcasts.apple.com/…" }, "updatedAt": "2026-12-03T12:00:00.000Z"
  }
}
```

---

### GET /api/v1/shows/:slug/episodes

**Public episodes (no auth)** — Published episodes of a show, newest first — the JSON alternative to parsing the RSS feed. Anonymous, CORS open, CDN-cached. Subscribe to the show webhooks (`episode.published` / `episode.updated` / `episode.unpublished`) to refresh immediately instead of polling.

- **Auth:** none
- **Access:** Anyone.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `slug` | path | string | yes | Show slug. |
| `limit` | query | integer | no | 1–100, default 20. |
| `offset` | query | integer | no | Default 0. |
| `q` | query | string | no | Search in titles and show notes. |

**Request**

```bash
curl "https://api.test.podcastor.eu/api/v1/shows/my-show/episodes?limit=10"
```

**Response**

```
{
  "episodes": [{
    "id": "ep_…", "guid": "4f6c…", "title": "Episode 1", "slug": "episode-1", "descriptionHtml": "<p>…</p>",
    "season": 1, "episodeNumber": 1, "episodeType": "full", "durationMs": 1800000, "publishedAt": "2026-12-01T07:00:00.000Z",
    "pageUrl": "https://my-show.podcastor.eu/episode-1", "embedUrl": "https://embed.podcastor.eu/ep_…",
    "audio": { "url": "https://media.podcastor.eu/e/ab12cd34ef-1/episode-1.mp3", "length": 28800417, "type": "audio/mpeg" },
    "video": null, "artworkUrl": null, "chaptersUrl": null, "transcriptUrl": null, "chapters": []
  }],
  "total": 1, "limit": 10, "offset": 0
}
```

> Webhook payloads carry the same episode object; they are signed `X-Webhook-Signature: sha256=HMAC_SHA256(secret, "<X-Webhook-Timestamp>.<raw body>")`.

---

### POST /api/shows

**Create a show** — Creates a show (slug = its subdomain, permanent). Also `GET /api/shows`, `GET|PATCH|DELETE /api/shows/:id`. Fields: title, slug, subtitle, description (Markdown), author, ownerName, ownerEmail, artworkMediaId (JPEG/PNG library image), language (BCP-47), categories (≤3 Apple categories {category, subcategory?}), explicit, showType (episodic|serial), copyright, websiteUrl, locked, funding[{url,label}], persons[{name,role,group,href,img}], medium, itemLimit, redirectUrl (moving away → 301 + itunes:new-feed-url), visibility (public|unlisted|private), feedSlug, directories {apple, spotify, youtube, amazon, pocketcasts, overcast, podcastindex}.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Editor in the workspace (`X-Workspace-Id` or the active one).

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/shows -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"title":"My Show","slug":"my-show","language":"en","categories":[{"category":"Technology"}],"author":"Me","ownerName":"Me","ownerEmail":"me@example.com"}'
```

**Response**

```
{ "id": "show_…", "slug": "my-show", "feedUrl": "https://feeds.podcastor.eu/my-show.xml", "podcastGuid": "…", … }
```

> 422 with {field, reason} for an invalid, reserved or taken slug and for invalid metadata.

---

### POST /api/shows/:id/episodes

**Create an episode (draft)** — Creates a draft. Also `GET /api/shows/:id/episodes`, `GET|PATCH|DELETE /api/shows/:id/episodes/:eid`. Fields: title, description (Markdown show notes), summary, audioMediaId and/or videoMediaId, artworkMediaId, durationMs, season, episodeNumber, episodeType (full|trailer|bonus), explicit, chapters [{startTime, title, url?, img?}], soundbites [{startTime, duration, title?}], transcriptVttMediaId, transcriptSrtMediaId, transcriptLanguage, origin, originId. The guid is assigned once and never changes; a deleted episode tombstones its guid.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Editor.

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/shows/show_…/episodes -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"title":"Episode 1","audioMediaId":"med_…","description":"**Notes**"}'
```

**Response**

```
{ "id": "ep_…", "guid": "4f6c…", "status": "draft", … }
```

---

### POST /api/shows/:id/episodes/:eid/publish

**Publish or schedule an episode** — Body `{mode:"now"}` or `{mode:"schedule", publishAt}`. Publishes the files at immutable `media.` URLs (a changed file = new URL version, same guid), rebuilds the stored feeds, purges the edge, pings WebSub + Podcast Index, fires `episode.published`. Also `POST …/unpublish`, `POST …/unschedule`, `GET …/checks` (pre-publish checks), `POST …/fix {kind: normalize|convert|artwork|show-artwork|transcribe}` (202 ConvertHippo job; the show-level `POST /api/shows/{id}/fix-artwork` does the same for the show artwork), `GET|PUT …/transcript {text|mediaId, language}`.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Editor.

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/shows/show_…/episodes/ep_…/publish -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"mode":"schedule","publishAt":"2026-12-24T07:00:00Z"}'
```

**Response**

```
{ "id": "ep_…", "status": "scheduled", "publishAt": "2026-12-24T07:00:00.000Z", "assets": [{ "kind": "audio", "url": "https://media.podcastor.eu/e/…/episode-1.mp3", "size": 28800417 }] }
```

---

### POST /api/shows/import

**Import a podcast from its RSS feed** — Body `{feedUrl, itemLimit?, slug?}` → `202 {id}`. In the background: creates the show and episodes with the ORIGINAL guids and dates, streams every enclosure into the encrypted media store (2 at a time, resumable), keeps artwork, chapters and transcripts. Follow `GET /api/shows/import/:id`. Libsyn and any standard RSS host.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Editor.

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/shows/import -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"feedUrl":"https://feeds.example.com/show.xml","itemLimit":2}'
```

**Response**

```
{ "id": "imp_…", "status": "pending" }
```

---

### POST /api/shows/:id/webhooks

**Add a webhook** — Body `{url, events?}` (events: episode.published, episode.updated, episode.unpublished). Returns the signing secret ONCE. Deliveries: POST JSON with `X-Webhook-Event`, `X-Webhook-Timestamp`, `X-Webhook-Signature: sha256=<hex HMAC-SHA256(secret, timestamp + "." + body)>`, 3 attempts. Also `GET /api/shows/:id/webhooks`, `DELETE /api/shows/:id/webhooks/:wid`; private feed tokens: `GET|POST /api/shows/:id/tokens`, `DELETE /api/shows/:id/tokens/:tid`; `GET /api/shows/:id/stats?days=30`, `GET /api/shows/:id/pings`.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Workspace admin.

**Request**

```bash
curl -X POST https://api.test.podcastor.eu/api/shows/show_…/webhooks -H "Authorization: Bearer sk_your_key_here" -H "Content-Type: application/json" -d '{"url":"https://example.com/hooks/podcast"}'
```

**Response**

```
{ "webhook": { "id": "wh_…", "url": "https://example.com/hooks/podcast", "events": ["episode.published","episode.updated","episode.unpublished"] }, "secret": "whsec_…" }
```

---

## Notes for automated callers

- Always send the `Authorization: Bearer sk_...` header; there is no cookie/session auth here.
- On `429`/`403` with a `Retry-After` header, wait that many seconds before retrying.
- Treat any non-2xx JSON `error` field as the human-readable failure reason.
- File downloads (`GET /api/v1/files/:id`) return raw bytes, not JSON.
