# LongStories API

Make videos from code: pick a universe, send a prompt, a script or audio, and get a video file back.

- Machine-readable description (OpenAPI 3.1): https://longstories.ai/api/v1/openapi.json
- Web page: https://longstories.ai/resources/api

## Authentication

Send your API key in the `x-api-key` header. Find it in your account settings: https://longstories.ai/settings. API access comes with the Creator plan: https://longstories.ai/pricing. Earlier plans that had API access keep it.

Every answer is JSON. A success is `{ "data": ..., "requestId": "..." }`; an error is `{ "error": ... }` (see Errors).

## How a video is made

1. `POST /api/v1/universe/{slug}/create` starts the video and answers at once with `data.requestId` (it starts with `run_`).
2. `GET /api/v1/universe/status?requestId=...` every 30 seconds until `isCompleted` is true.
3. `output.url` is the video file.

## Guides

### Keep the same characters in every video

The API does not remember the characters of your last video. Each create request uses exactly the characters it sends in `characters`.

Leave `characters` out and the video makes new characters from your prompt, so they look different every time. The universe's cast is not added for you.

To keep a cast: save each character once (on [your characters page](https://longstories.ai/characters) or with `POST /api/v1/characters`), read their ids with `GET /api/v1/characters`, and send the same ids in every create request. A saved character keeps its look and its voice.

An object such as `{ "name": "Luna", "description": "A wise owl" }` only describes a character for that one video. It is not saved and does not carry over.

If you send two saved characters with the same name, the video uses the first one. A universe set to "Only its cast" refuses characters that are not in its cast (`universe_cast_only`).

**Every request sends the same ids**

```json
{
  "prompt": "Catboy Logan helps a lost kitten find home",
  "duration": "60",
  "animationPreset": "fast",
  "videoFormat": "9:16",
  "characters": [
    "80d3a3c9-3673-46c3-8fab-47d3acf5b72d",
    "db129137-0aeb-498c-adc4-b36ab54303c9"
  ]
}
```

### Make a video from a song or a narration

Upload the audio with `POST /api/v1/voiceover/upload`. Then call create with `voiceoverKey` and `voiceoverDuration` set to the `voiceoverKey` and `duration` the upload returned. For a song, add `"audioKind": "song"`; its lyrics are transcribed from the audio.

`voiceoverDuration` is required with `voiceoverKey`. A request without it, or with a value 1 second or more away from the upload, is refused.

**Song video**

```python
import time
import requests

API = "https://longstories.ai/api/v1"
HEADERS = {"x-api-key": "YOUR_API_KEY", "LongStories-Version": "2026-10-15"}

with open("my-song.mp3", "rb") as song:
    upload = requests.post(f"{API}/voiceover/upload", headers=HEADERS, files={"file": song}).json()["data"]

create = requests.post(
    f"{API}/universe/the-adventures-of-catboy-logan/create",
    headers={**HEADERS, "Idempotency-Key": "veggie-song-1"},
    json={
        "prompt": "Catboy Logan and Blaze sing about vegetables",
        "voiceoverKey": upload["voiceoverKey"],
        "voiceoverDuration": upload["duration"],
        "audioKind": "song",
        "animationPreset": "pro",
        "characters": ["80d3a3c9-3673-46c3-8fab-47d3acf5b72d", "db129137-0aeb-498c-adc4-b36ab54303c9"],
    },
)
create.raise_for_status()
run_id = create.json()["data"]["requestId"]

while True:
    status = requests.get(f"{API}/universe/status", headers=HEADERS, params={"requestId": run_id}).json()["data"]
    if status["isCompleted"]:
        break
    time.sleep(30)

print(status["output"]["url"] if status["isSuccess"] else status["error"])
```

### Use your own script

Send `userScript` instead of `prompt` to skip script writing. The script must be in the LongStories script format, with scenes, shots and `@Handles`; see the [scripting guide](https://longstories.ai/resources/scripting-guide). A script in another form is refused with `needs_canonical_rewrite` before any credit is used.

A `@Handle` in a script does not select a saved character by itself. Send the character ids in `characters`, and write each one in the script with its `mentionHandle` from `GET /api/v1/characters` (for example `@CatBoy`). A `@Handle` that matches none of them becomes a new character.

## Endpoints

### Create a video

`POST /api/v1/universe/{slug}/create`

Start a video in a universe. Answers at once with a run id; poll the status endpoint for the video.

Rate limit: 100 per minute per key, shared with estimate and status.

Parameters:

| Field | Type | Required | What it does |
|---|---|---|---|
| `slug` | string (path) | Yes | The universe's slug: the last part of its address, `https://longstories.ai/universes/{slug}`. Public universes and your own. |

Body (`application/json`):

| Field | Type | Required | What it does |
|---|---|---|---|
| `prompt` | string | Unless `userScript` or `voiceoverKey` | What the video is about. Required unless you send `userScript` or `voiceoverKey`. |
| `duration` | string | No | Target length in seconds, as a string. "15", "30", "60", "180", "300" and "600" have a fixed price; other values get an approximate price. A script or uploaded audio sets its own length. Default: `"60"`. |
| `animation` | boolean | No | Old switch: `false` makes a video without animation. Prefer `animationPreset`; if you send both, they must agree. Default: `true`. |
| `animationPreset` | string | No | Animation quality: `static` (storyboard, no animation), `mini`, `fast`, `pro` or `ultra`. Omit it to use the universe's default. Values: `static`, `mini`, `fast`, `pro`, `ultra`. |
| `imagePreset` | string | No | Storyboard images, for `animationPreset: "static"` only: `basic` (cheaper) or `advanced` (default). `legacy` works only for accounts created before 16 September 2026. Animated presets ignore it. Values: `basic`, `advanced`, `legacy`. |
| `language` | string | No | Language code such as "en" or "es". Omit it and the language is detected from the prompt. |
| `characters` | array of object or string | No | The characters of this video. Each item is either the id of a saved character (from `GET /api/v1/characters`), which keeps its look and voice, or an object `{ name, description, appearance?, clothing? }` that describes a character for this video only (it is not saved). If you leave this field out, the video makes new characters from your prompt, and the universe's cast is not added for you. To keep the same characters across videos, send the same ids on every request. |
| `visualStyleId` | string (uuid) | No | A visual style of the universe. Omit it to use the universe's default style behavior. |
| `preferAiStyle` | boolean | No | A hint to let AI choose the style. It does not override a universe whose default is AI style; send `visualStyleId` to force a style. |
| `removeWatermark` | boolean | No | Remove the watermark. Your plan must include watermark removal; without it the request still succeeds and the watermark stays. Default: `false`. |
| `videoFormat` | string | No | Aspect ratio. Omit it to use the universe's setting. Values: `9:16`, `16:9`. |
| `captions` | boolean | No | Captions on or off. Omit it to use the universe's setting. |
| `captionsStyle` | string | No | Caption look. Previews: https://longstories.ai/resources/captions Values: `default`, `minimal`, `neon`, `cinematic`, `fancy`, `tiktok`, `highlight`, `gradient`, `intellectual`, `vida`, `manuscripts`, `subtitle`, `modern`, `bounce`, `popcorn`, `typewriter`, `handwritten`, `karaoke`, `retro`, `gaming`. |
| `captionsPosition` | string | No | Caption placement. Values: `center`, `bottom`, `top`. |
| `userScript` | string | No | Your own script in LongStories script format, so no script is written for you. Cannot be sent with `voiceoverKey`. A script that is not in the format is refused with `needs_canonical_rewrite`. |
| `voiceoverKey` | string | No | The `voiceoverKey` from `POST /api/v1/voiceover/upload`: a narration or a song the video follows. Cannot be sent with `userScript`. |
| `voiceoverDuration` | number | With `voiceoverKey` | Required with `voiceoverKey`: the `duration` the upload returned, in seconds. A value 1 second or more away from the uploaded audio is refused. |
| `audioKind` | string | No | What the uploaded audio is: `voiceover` (default) or `song`. Requires `voiceoverKey`. Values: `voiceover`, `song`. |
| `songPerformance` | object | No | Songs only: whether characters sing on camera and who leads. |
| `audioTranscript` | string | No | The exact spoken words of an uploaded voiceover, used for captions and timing. Requires `voiceoverKey`. Not for songs: their lyrics are transcribed from the audio. |
| `musicConfig` | object | No | Background music under the narration: `{ musicSlug, volume?, loop?, enabled? }`. `musicSlug` is a catalog track or one from `POST /api/v1/music/upload`. `{ "enabled": false }` turns off the universe's default music. Volume 0 to 1 (default 0.3). |

- Send one of `prompt`, `userScript` or `voiceoverKey`.
- Add an `Idempotency-Key` header (up to 256 characters) to retry safely. For a fixed-price request, a retry with the same key and body returns the same video and does not charge again; the same key with a different body is refused.
- Your account makes one video at a time through the API. A second request is accepted and waits as `QUEUED` until the first one ends.

**Request**

```bash
curl -X POST https://longstories.ai/api/v1/universe/the-adventures-of-catboy-logan/create \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "LongStories-Version: 2026-10-15" \
  -H "Idempotency-Key: catboy-episode-12" \
  -d '{
  "prompt": "Catboy Logan helps a lost kitten find home",
  "duration": "60",
  "animationPreset": "fast",
  "videoFormat": "9:16",
  "characters": [
    "80d3a3c9-3673-46c3-8fab-47d3acf5b72d",
    "db129137-0aeb-498c-adc4-b36ab54303c9"
  ]
}'
```

**Response**

```json
{
  "data": {
    "requestId": "run_06gje4epb3crc9jna7kod5el01",
    "status": "QUEUED",
    "estimatedDuration": 600000,
    "estimatedCredits": 299
  },
  "requestId": "3f2c9a4e-0b7d-4c55-9a52-5a1d2f6e8b10"
}
```

### Check a video

`GET /api/v1/universe/status?requestId={run id}`

The state of a video you started. Poll it every 30 seconds until `isCompleted` is true.

Rate limit: 100 per minute per key, shared with create and estimate.

Parameters:

| Field | Type | Required | What it does |
|---|---|---|---|
| `requestId` | string (query) | Yes | The `data.requestId` of the create response. It starts with `run_`. |

- `status` is one of `WAITING_FOR_DEPLOY`, `QUEUED`, `EXECUTING`, `REATTEMPTING`, `FROZEN`, `COMPLETED`, `CANCELED`, `FAILED`, `CRASHED`, `INTERRUPTED`, `SYSTEM_FAILURE`, `TIMED_OUT`, `DELAYED`, `EXPIRED`.
- When `isSuccess` is true, `output.url` is the video file and `output.projectId` is the project in your library.
- A video usually takes 5 to 20 minutes, longer for long or `ultra` videos.

**Request**

```bash
curl "https://longstories.ai/api/v1/universe/status?requestId=run_06gje4epb3crc9jna7kod5el01" \
  -H "x-api-key: YOUR_API_KEY"
```

**Response when the video is ready**

```json
{
  "data": {
    "status": "COMPLETED",
    "isCompleted": true,
    "isSuccess": true,
    "output": {
      "url": "https://.../out.mp4",
      "size": 21267933,
      "projectId": "1917b8a2-498f-40b7-8097-fef38030eec1"
    },
    "error": null,
    "creditsUsed": 299
  },
  "requestId": "..."
}
```

### Price a video

`POST /api/v1/universe/{slug}/estimate`

The credits a create request would cost, without starting it. Same body as create.

Rate limit: 100 per minute per key, shared with create and status.

Parameters:

| Field | Type | Required | What it does |
|---|---|---|---|
| `slug` | string (path) | Yes | The universe's slug: the last part of its address, `https://longstories.ai/universes/{slug}`. Public universes and your own. |

- Send exactly the body you will send to create (see its fields above).

**Request**

```bash
curl -X POST https://longstories.ai/api/v1/universe/the-adventures-of-catboy-logan/estimate \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "LongStories-Version: 2026-10-15" \
  -d '{ "prompt": "Catboy Logan helps a lost kitten find home", "duration": "60", "animationPreset": "fast" }'
```

**Response**

```json
{
  "data": { "estimatedDuration": 60000, "estimatedCredits": 262 },
  "requestId": "..."
}
```

### List your characters

`GET /api/v1/characters`

Your saved characters, newest first (up to 100), with the `id` to send in `characters`.

Rate limit: 30 per minute per key.

- A character's id is also the last part of its address: `https://longstories.ai/characters/{id}`.

**Request**

```bash
curl https://longstories.ai/api/v1/characters -H "x-api-key: YOUR_API_KEY"
```

**Response**

```json
{
  "data": {
    "characters": [
      {
        "id": "80d3a3c9-3673-46c3-8fab-47d3acf5b72d",
        "name": "Cat Boy",
        "mentionHandle": "CatBoy",
        "description": "A brave young hero",
        "appearance": "...",
        "clothing": "...",
        "personality": "",
        "speech": "",
        "characterPrompt": "...",
        "imageUrl": "https://...",
        "createdAt": "2026-07-16T19:04:11.263687+00:00"
      }
    ]
  },
  "requestId": "..."
}
```

### Save a character

`POST /api/v1/characters`

Save a character from text (JSON) or from a photo (multipart, field `image`). Use the returned `id` in `characters`.

Rate limit: 30 per minute per key.

Body (`application/json`):

| Field | Type | Required | What it does |
|---|---|---|---|
| `name` | string | Yes | The character's name. |
| `description` | string | Yes | Who the character is. |
| `appearance` | string | No | How the character looks. |
| `clothing` | string | No | What the character wears. |
| `personality` | string | No | How the character behaves. |
| `speech` | string | No | How the character talks. |

Body (`multipart/form-data`):

| Field | Type | Required | What it does |
|---|---|---|---|
| `image` | file | Yes | A JPEG, PNG or WebP photo up to 25 MB. Each person in it becomes a saved character. |

- Your plan's character limit applies.

**Request**

```bash
curl -X POST https://longstories.ai/api/v1/characters \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{ "name": "Cat Boy", "description": "A brave young hero", "clothing": "Blue cat suit" }'
```

**Response**

```json
{
  "data": { "characters": [ { "id": "80d3a3c9-3673-46c3-8fab-47d3acf5b72d", "name": "Cat Boy", "...": "..." } ] },
  "requestId": "..."
}
```

### Upload a narration or a song

`POST /api/v1/voiceover/upload`

Upload audio for a video to follow. Send the returned `voiceoverKey` and `duration` to create.

Rate limit: 10 per minute per key.

Body (`multipart/form-data`):

| Field | Type | Required | What it does |
|---|---|---|---|
| `file` | file | Yes | MP3, WAV, M4A, AAC, OGG, OPUS, FLAC or WebM, up to 128 MB. Your plan's audio length limit applies. |
| `originalName` | string | No | A file name to keep with the upload. |

- The request needs a `Content-Length` header; curl and most HTTP clients add it.

**Request**

```bash
curl -X POST https://longstories.ai/api/v1/voiceover/upload \
  -H "x-api-key: YOUR_API_KEY" \
  -F "file=@my-song.mp3"
```

**Response**

```json
{
  "data": {
    "voiceoverKey": "video-creation/voiceovers/af7df29397ac3e5dd647430f15789e3c.mp3",
    "duration": 26.832,
    "originalName": "my-song.mp3"
  },
  "requestId": "..."
}
```

### Upload background music

`POST /api/v1/music/upload`

Upload your own track. Send the returned `musicSlug` as `musicConfig.musicSlug` in any later video.

Rate limit: 10 per minute per key.

Body (`multipart/form-data`):

| Field | Type | Required | What it does |
|---|---|---|---|
| `file` | file | Yes | Same formats and size limit as the narration upload. |
| `title` | string | No | The track's title. Default: the file name. |

**Request**

```bash
curl -X POST https://longstories.ai/api/v1/music/upload \
  -H "x-api-key: YOUR_API_KEY" \
  -F "file=@my-track.mp3" \
  -F "title=My Track"
```

**Response**

```json
{
  "data": { "musicSlug": "user_abc123", "title": "My Track", "duration": 187 },
  "requestId": "..."
}
```

### List music

`GET /api/v1/music`

The music catalog and your uploaded tracks, with the `musicSlug` to send in `musicConfig`.

Rate limit: 30 per minute per key.

**Request**

```bash
curl https://longstories.ai/api/v1/music -H "x-api-key: YOUR_API_KEY"
```

**Response**

```json
{
  "data": {
    "catalog": [
      { "musicSlug": "temple_of_treasures", "title": "Temple of Treasures", "duration": 180, "category": "adventure", "tags": ["epic"] }
    ],
    "customTracks": [ { "musicSlug": "user_abc123", "title": "My Track", "duration": 187 } ]
  },
  "requestId": "..."
}
```

### Delete an uploaded track

`DELETE /api/v1/music/{musicSlug}`

Delete one of your uploaded tracks. Catalog tracks cannot be deleted.

Rate limit: 30 per minute per key.

Parameters:

| Field | Type | Required | What it does |
|---|---|---|---|
| `musicSlug` | string (path) | Yes | The `musicSlug` the upload returned. |

**Request**

```bash
curl -X DELETE https://longstories.ai/api/v1/music/user_abc123 -H "x-api-key: YOUR_API_KEY"
```

**Response**

```json
{
  "data": { "deleted": true, "musicSlug": "user_abc123" },
  "requestId": "..."
}
```

## Versions

- The API has dated versions. Send the `LongStories-Version` header to choose one; we recommend sending it on every request, so your integration never changes under you.
- Without the header, a call uses the newest version that existed on the day your API key was created. An answer to an authenticated call names the version it used in its `LongStories-Version` header.
- An older version keeps working: the API converts its requests to the newest format. Adding a field or an endpoint does not make a new version; renaming, removing or changing the meaning of something does.

### 2026-10-15

One name per field and strict request bodies.

- Create and estimate: send `prompt` (not `projectPrompt`), `captions` (not `captionsEnabled`), and `animationPreset` as one of `static`, `mini`, `fast`, `pro`, `ultra` (older spellings such as `pro_animation` or `just_storyboard` are refused). A field the API does not know is refused instead of ignored.

### 2026-10-14

The first dated version: the API as it was before versions.

## Errors

```json
{
  "error": {
    "code": "VAL_INVALID_FORMAT",
    "message": "Invalid format provided",
    "requestId": "3f2c9a4e-0b7d-4c55-9a52-5a1d2f6e8b10",
    "details": { "errors": [ { "path": ["voiceoverDuration"], "message": "voiceoverDuration must be a positive number when voiceoverKey is provided" } ] },
    "docs": "https://longstories.ai/resources/api#errors"
  }
}
```

- `message` names the kind of error. What to fix is in `details`: `details.errors` lists each field problem, `details.reason` or `details.message` explains the rest, and `details.code` names a business rule such as `universe_cast_only` or `needs_canonical_rewrite`.
- Give us the `requestId` when you contact support: it finds your request in our log.

| Code | HTTP | Message |
|---|---|---|
| `AUTH_MISSING_KEY` | 401 | API key is required |
| `AUTH_INVALID_KEY` | 401 | Invalid API key provided |
| `AUTH_EXPIRED_KEY` | 401 | API key has expired |
| `VAL_MISSING_FIELD` | 400 | Required field is missing |
| `VAL_INVALID_FORMAT` | 400 | Invalid format provided |
| `VAL_CONSTRAINT_VIOLATION` | 400 | Input violates constraints |
| `VAL_CONTENT_VIOLATION` | 400 | Content violates usage policies |
| `VAL_PAYLOAD_TOO_LARGE` | 413 | Payload is too large |
| `BIZ_INSUFFICIENT_CREDITS` | 402 | Insufficient credits to perform this operation |
| `BIZ_GENERATION_FAILED` | 500 | Failed to generate content |
| `BIZ_RESOURCE_NOT_FOUND` | 404 | Requested resource not found |
| `BIZ_INVALID_OPERATION` | 400 | Operation not allowed |
| `RATE_TOO_MANY_REQUESTS` | 429 | Too many requests, please try again later |
| `RATE_QUOTA_EXCEEDED` | 429 | API quota exceeded for the current period |
| `SRV_INTERNAL_ERROR` | 500 | Internal server error occurred |
| `SRV_DEPENDENCY_ERROR` | 502 | External service error |
| `SRV_MAINTENANCE` | 503 | Service is undergoing maintenance |

## Limits

- Rate limits count per API key over a sliding minute. Above the limit you get `429 RATE_TOO_MANY_REQUESTS` with `details.reset`.
- One video at a time per account: more create requests wait as `QUEUED`.
- Polling uses the same budget as create: poll every 30 seconds, not faster.

## Prices

A prompt video at the lowest resolution of each preset costs:

- Storyboard (`static`), 1 min: 272 credits
- Storyboard (`static`), 3 min: 745 credits
- Storyboard (`static`), 10 min: 2,435 credits
- `fast`, 1 min: 437 credits
- `fast`, 3 min: 1,246 credits
- `fast`, 10 min: 4,008 credits
- `pro`, 1 min: 715 credits
- `pro`, 3 min: 1,831 credits
- `pro`, 10 min: 5,384 credits

Use the estimate endpoint for the price of your exact request.

## Partner API

Machine-readable description (OpenAPI 3.1): https://longstories.ai/api/partner/v1/openapi.json

- For partners who resell LongStories videos and pay in US dollars. LongStories gives you a partner key; a normal API key is refused (`not_a_partner_key`).
- Base URL: `https://longstories.ai/api/partner/v1`. Send the key in the `x-api-key` header, from your server only.
- Every answer is `{ data, requestId }`; an error is `{ error }`, with the same shape as the main API.
- Prices come from `GET /prices` and `POST /quotes`. Both need your key.
- A music video uses a song uploaded with `POST /api/v1/voiceover/upload` and your partner key.

### Prices

`GET /api/partner/v1/prices`

The current price of each tier, resolution and video type, in USD a second.

Rate limit: 1,200 per minute per key, shared with balance and video reads.

- Price = USD a second × seconds, rounded up to whole seconds, with `minimum_billing_seconds` as the minimum.
- Prices can change. Read them from your code (for example every 10 minutes); do not copy them by hand.

**Request**

```bash
curl https://longstories.ai/api/partner/v1/prices -H "x-api-key: YOUR_PARTNER_KEY"
```

**Response**

```json
{
  "data": {
    "version": "…",
    "minimum_billing_seconds": …,
    "max_video_seconds": 600,
    "prices": [
      { "type": "story", "tier": "fast", "resolution": "480p", "usd_per_second": … }
    ]
  },
  "requestId": "…"
}
```

### Balance

`GET /api/partner/v1/balance`

Your prepaid balance in USD. A video's price leaves it when the video starts.

Rate limit: 1,200 per minute per key, shared with price and video reads.

**Request**

```bash
curl https://longstories.ai/api/partner/v1/balance -H "x-api-key: YOUR_PARTNER_KEY"
```

**Response**

```json
{ "data": { "balance_usd": … }, "requestId": "…" }
```

### Quote a video

`POST /api/partner/v1/quotes`

The exact price of one video. Free; nothing is charged.

Rate limit: 120 per minute per key, shared with new videos.

Body (`application/json`):

| Field | Type | Required | What it does |
|---|---|---|---|
| `end_user` | string | Yes | Your id for the user who orders the video: 1 to 64 letters, digits, `.` `_` `:` `-`. Send your internal id, not an email or a name. |
| `type` | string | Yes | `story`: a video from an idea or a script. `music_video`: a video that follows an uploaded song. Values: `story`, `music_video`. |
| `tier` | string | Yes | The quality. `ultra` is for stories only. Values: `fast`, `pro`, `ultra`. |
| `resolution` | string | No | The quality of the animated clips. `GET /prices` lists what each tier and type sells. Values: `480p`, `720p`, `1080p`, `4k`. Default: `"480p"`. |
| `aspect_ratio` | string | No | Horizontal (`16:9`) or vertical (`9:16`). Values: `9:16`, `16:9`. Default: `"16:9"`. |
| `prompt` | string | A story needs `prompt` or `script` | The idea, up to 5,000 characters. For a music video, it is optional and guides the look. |
| `script` | string | A story needs `prompt` or `script` | A script in the [LongStories format](https://longstories.ai/resources/scripting-guide). The script sets the length. Do not send `duration_seconds` with it. |
| `duration_seconds` | integer | With a story `prompt` | The length of a video from an idea, in seconds. Values: `15`, `30`, `60`, `180`, `300`, `600`. |
| `song_upload_key` | string | With `music_video` | The `voiceoverKey` of a song uploaded with `POST /api/v1/voiceover/upload` and the same key. The video is as long as the song. |
| `characters` | array of object | No | With a `prompt`: up to 10 `{ "name", "description" }` that must be in the video. `name` up to 60 characters, `description` up to 1,000. Characters are not saved between videos. |
| `language` | string | No | The language of the narration and the dialogue, for example `en` or `es`. Recommended: without it, the language is detected first. |

- A quote checks every field, the script or the song, and computes the price. The content rules and your balance are checked when you make the video.
- For a script or a song, ask a quote: the length is measured first.

**Request**

```bash
curl -X POST https://longstories.ai/api/partner/v1/quotes \
  -H "x-api-key: YOUR_PARTNER_KEY" -H "Content-Type: application/json" \
  -d '{
    "end_user": "u_8f2c91",
    "type": "story",
    "tier": "pro",
    "resolution": "720p",
    "prompt": "A fox finds a treasure map in the snow",
    "duration_seconds": 60,
    "language": "en"
  }'
```

**Response**

```json
{ "data": { "price_usd": …, "usd_per_second": …, "billing_seconds": 60 }, "requestId": "…" }
```

### Make a video

`POST /api/partner/v1/videos`

Starts a video and holds its price from your balance. Same body as the quote, plus `max_price_usd`.

Rate limit: 120 per minute per key, shared with quotes.

Parameters:

| Field | Type | Required | What it does |
|---|---|---|---|
| `Idempotency-Key` | string (header) | Yes | A unique id for this video, for example your order id, up to 256 characters. Send the same key and body again to retry: you get the same video and pay once. The same key with a different body is refused (`idempotency_key_reused`). |

Body (`application/json`):

| Field | Type | Required | What it does |
|---|---|---|---|
| `end_user` | string | Yes | Your id for the user who orders the video: 1 to 64 letters, digits, `.` `_` `:` `-`. Send your internal id, not an email or a name. |
| `type` | string | Yes | `story`: a video from an idea or a script. `music_video`: a video that follows an uploaded song. Values: `story`, `music_video`. |
| `tier` | string | Yes | The quality. `ultra` is for stories only. Values: `fast`, `pro`, `ultra`. |
| `resolution` | string | No | The quality of the animated clips. `GET /prices` lists what each tier and type sells. Values: `480p`, `720p`, `1080p`, `4k`. Default: `"480p"`. |
| `aspect_ratio` | string | No | Horizontal (`16:9`) or vertical (`9:16`). Values: `9:16`, `16:9`. Default: `"16:9"`. |
| `prompt` | string | A story needs `prompt` or `script` | The idea, up to 5,000 characters. For a music video, it is optional and guides the look. |
| `script` | string | A story needs `prompt` or `script` | A script in the [LongStories format](https://longstories.ai/resources/scripting-guide). The script sets the length. Do not send `duration_seconds` with it. |
| `duration_seconds` | integer | With a story `prompt` | The length of a video from an idea, in seconds. Values: `15`, `30`, `60`, `180`, `300`, `600`. |
| `song_upload_key` | string | With `music_video` | The `voiceoverKey` of a song uploaded with `POST /api/v1/voiceover/upload` and the same key. The video is as long as the song. |
| `characters` | array of object | No | With a `prompt`: up to 10 `{ "name", "description" }` that must be in the video. `name` up to 60 characters, `description` up to 1,000. Characters are not saved between videos. |
| `language` | string | No | The language of the narration and the dialogue, for example `en` or `es`. Recommended: without it, the language is detected first. |
| `max_price_usd` | number | `POST /videos` only | The most your user agreed to pay, normally the quoted `price_usd`. A higher price is refused with `price_above_max` and charges nothing. |
| `webhook_url` | string (URL) | No | An https URL, up to 2,048 characters. It gets a signed call when the video ends (see Webhooks). |
| `test_result` | string | No | Test keys only: how the free sample video ends. Default: `completed`. A live key that sends it gets a 400. Values: `completed`, `failed`. |

- The answer has HTTP status `202`. Save `id`.
- The call takes a few seconds, up to about 15 with many `characters`. Use a client timeout of 60 seconds.
- When the video is done, the held price is charged. When it fails, the price is given back.

**Request**

```bash
curl -X POST https://longstories.ai/api/partner/v1/videos \
  -H "x-api-key: YOUR_PARTNER_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: order_20261103_0042" \
  -d '{
    "end_user": "u_8f2c91",
    "type": "story",
    "tier": "pro",
    "resolution": "720p",
    "prompt": "A fox finds a treasure map in the snow",
    "duration_seconds": 60,
    "language": "en",
    "max_price_usd": QUOTED_PRICE_USD,
    "webhook_url": "https://example.com/longstories/webhook"
  }'
```

**Response (202)**

```json
{
  "data": { "id": "9ad1b3d6-c57d-41d3-8d7e-b3b95fb91718", "status": "queued", "end_user": "u_8f2c91", "price_usd": … },
  "requestId": "…"
}
```

### Check a video

`GET /api/partner/v1/videos/{id}`

Status, charge and the video link. Without a webhook, ask every 30 seconds until `completed` or `failed`.

Rate limit: 1,200 per minute per key, shared with price and balance reads.

Parameters:

| Field | Type | Required | What it does |
|---|---|---|---|
| `id` | string (path) | Yes | The `id` that `POST /videos` returned. |

- `status` is one of `queued`, `processing`, `completed`, `failed`. 10 of your videos are made at the same time; more wait as `queued`.
- A video usually takes 20 to 40 minutes. A long Pro video or a music video can take an hour.
- `charged_usd` is `null` while the video is made, the price when it is done, and `0` when it failed.
- The `video_url` does not expire. Download the MP4 once and serve it from your own storage.

**Request**

```bash
curl https://longstories.ai/api/partner/v1/videos/9ad1b3d6-c57d-41d3-8d7e-b3b95fb91718 -H "x-api-key: YOUR_PARTNER_KEY"
```

**Response when the video is done**

```json
{
  "data": {
    "id": "9ad1b3d6-c57d-41d3-8d7e-b3b95fb91718",
    "status": "completed",
    "end_user": "u_8f2c91",
    "price_usd": …,
    "charged_usd": …,
    "video_url": "https://…/out.mp4",
    "duration_seconds": 60.081,
    "error": null,
    "created_at": "2026-11-03T12:01:43.577131+00:00",
    "updated_at": "2026-11-03T12:29:39.444725+00:00"
  },
  "requestId": "…"
}
```

### Webhooks

Send `webhook_url` with `POST /videos`. When the video ends and its charge or refund is settled, LongStories POSTs JSON to that URL. Polling `GET /videos/{id}` still works.

Headers:

| Field | Type | Required | What it does |
|---|---|---|---|
| `Content-Type` | header | Yes | `application/json`. |
| `LongStories-Event-Id` | header | Yes | The `id` of the body. |
| `LongStories-Signature` | header | Yes | `t=<unix seconds>,v1=<signature>`. The signature is the hex HMAC-SHA256 of `<t>.<raw body>` with your webhook secret, which LongStories gives you with your key. |

Body:

| Field | Type | Required | What it does |
|---|---|---|---|
| `id` | string | Yes | `<video id>:<type>`. Use it to find a call that came twice. |
| `type` | string | Yes | How the video ended. Values: `video.completed`, `video.failed`. |
| `created_at` | string (ISO time) | Yes | When the call was made. |
| `data` | object | Yes | The same object as the `data` of `GET /videos/{id}`. |

- Answer with any 2xx within 10 seconds. Otherwise LongStories tries again for about 10 hours.
- A call can come more than once. Use the event id to do the work once.
- Check the signature on the raw body, before you parse it, and refuse a `t` older than 5 minutes.

**Webhook body**

```json
{
  "id": "9ad1b3d6-c57d-41d3-8d7e-b3b95fb91718:video.completed",
  "type": "video.completed",
  "created_at": "2026-11-03T12:30:02.118Z",
  "data": {
    "id": "9ad1b3d6-c57d-41d3-8d7e-b3b95fb91718",
    "status": "completed",
    "end_user": "u_8f2c91",
    "price_usd": …,
    "charged_usd": …,
    "video_url": "https://…/out.mp4",
    "duration_seconds": 60.081,
    "error": null,
    "created_at": "2026-11-03T12:01:43.577131+00:00",
    "updated_at": "2026-11-03T12:29:39.444725+00:00"
  }
}
```

**Check the signature**

```python
import hashlib
import hmac
import time

def is_longstories_call(raw_body: bytes, signature_header: str, secret: str) -> bool:
    parts = dict(item.split("=", 1) for item in signature_header.split(",") if "=" in item)
    timestamp = parts.get("t", "")
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300:
        return False
    signed = timestamp.encode() + b"." + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))
```

### Test key

- LongStories can give you a second key: a test key. With it, `POST /videos` checks and prices the request like a live key, with the same errors (`price_above_max` too). It charges nothing and makes no video.
- The test video is at once `completed` with a fixed sample MP4 and `charged_usd: 0`. Send `"test_result": "failed"` to get a `failed` video.
- Its webhook comes within a minute.
- With the test key, `GET /videos/{id}` reads test videos only, for 30 days. Prices, balance and quotes answer as with the live key.

### Partner errors

| HTTP | `code` | `details.code` | Meaning |
|---|---|---|---|
| 401 | `AUTH_INVALID_KEY` | `not_a_partner_key` | A normal LongStories key, not a partner key. |
| 400 | `VAL_MISSING_FIELD` |  | A required field or header is missing; `details.field` names it. |
| 400 | `VAL_INVALID_FORMAT` |  | A field has a wrong value; `details.field` and `details.reason` say which and why. |
| 400 | `VAL_INVALID_FORMAT` | `partner_price_unavailable` | This tier, resolution and type is not sold. Choose one from `GET /prices`. |
| 400 | `VAL_INVALID_FORMAT` | `song_not_found` | No song with this key, or another key uploaded it. |
| 400 | `VAL_INVALID_FORMAT` | `needs_canonical_rewrite` | The script is not in the LongStories format; `details.details.issues` says what to change. |
| 400 | `VAL_INVALID_FORMAT` | `test_result_needs_test_key` | A live key sent `test_result`. |
| 401 | `AUTH_INVALID_KEY` | `test_key_not_allowed` | A test key was sent to an API other than the partner endpoints and the song upload. |
| 400 | `VAL_CONTENT_VIOLATION` |  | The idea, script or song breaks the content rules. Do not retry the same content. |
| 400 | `BIZ_INVALID_OPERATION` | `price_above_max` | The price is above `max_price_usd`; `details.price_usd` is the price now. |
| 400 | `BIZ_INVALID_OPERATION` | `creation_quote_changed` | The price changed while the video started. Quote again. |
| 400 | `BIZ_INVALID_OPERATION` | `idempotency_key_reused` | This Idempotency-Key was used for a different request. |
| 402 | `BIZ_INSUFFICIENT_CREDITS` | `insufficient_balance` | Your balance is lower than the price. |
| 404 | `BIZ_RESOURCE_NOT_FOUND` |  | No video with this id for your key. |
| 429 | `RATE_TOO_MANY_REQUESTS` |  | Too many requests; `details.reset` says when to send again. |
