# AiVideoEditor API quickstart

Base URL: `https://<your-app-host>/api/v1` (local dev: `http://localhost:3006/api/v1`).

## Authentication

Create a product key in **Developers** in the workspace navigation (`/app/developers`). The plaintext
key (`pk_v1_…`) is shown **exactly once**; only a hash and a short prefix are stored.
Send it as a bearer token:

```bash
curl -H "Authorization: Bearer $PUBLISHER_KEY" https://app.example.com/api/v1/usage
```

Keys carry explicit scopes (`accounts:read`, `media:write`, `posts:read`,
`posts:write`, `posts:publish`, `usage:read`, `webhooks:manage`) and an optional
account allowlist. A **draft-only** key omits `posts:publish` and therefore cannot
publish, schedule, cancel or retry. Keys can never create other keys or change
billing. Revoking a key **pauses its unsent jobs** as `requires_action`: nothing is
deleted, and the revocation UI shows the affected pending-job count first.

## Ground rules

- **Every mutation** requires an `Idempotency-Key` header. Same key + same body →
  the same recorded result (same delivery IDs). Same key + different body →
  `409 idempotency_conflict`.
- Edits and scheduling require `expectedVersion`; a stale version returns
  `409 revision_conflict` with the current version in `error.details.currentVersion`.
- `202` from publish/schedule means **accepted for dispatch**, never "published".
  Track outcomes with `GET /posts/{id}`, customer webhooks, or bounded polling.
- Rate limits are **technical speed limits per workspace** (60/120/240 req/min by
  plan; `429` + `Retry-After`). There is no request or posting quota: posting is
  unlimited on every paid plan.
- Errors use the normalized envelope: `{ error: { code, message, fieldErrors?,
  destinationErrors?, retryable?, retryAfterSeconds?, requestId } }`.

## End-to-end: draft → validate → publish → observe

The example requires Bash, `curl`, `jq`, Node 22+, an active workspace,
a connected Facebook Page or LinkedIn destination, and a key with
`accounts:read`, `posts:read`, `posts:write` and `posts:publish`. Set
`ACCOUNT_ID` to a permitted destination from `/accounts`; check its text format
support in `/capabilities`. Running the publish command posts real content.

```bash
set -euo pipefail
BASE="${PUBLISHER_API_URL:?Set the AiVideoEditor origin}/api/v1"
AUTH="Authorization: Bearer ${PUBLISHER_KEY:?Set the product key}"
JSON="Content-Type: application/json"
new_key() { node -e 'console.log(require("node:crypto").randomUUID())'; }

curl --fail-with-body -sS -H "$AUTH" "$BASE/accounts"
curl --fail-with-body -sS -H "$AUTH" "$BASE/capabilities"
: "${ACCOUNT_ID:?Choose a permitted text destination from the responses above}"

# Save this key and body; reuse both if the connection fails ambiguously.
CREATE_KEY=$(new_key)
DRAFT_BODY=$(jq -n --arg account "$ACCOUNT_ID" '{caption:"A new update from our team.",mediaIds:[],brandFolderId:null,destinations:[{accountId:$account,format:"text"}]}')
DRAFT=$(curl --fail-with-body -sS -X POST -H "$AUTH" \
  -H "Idempotency-Key: $CREATE_KEY" -H "$JSON" \
  "$BASE/posts" -d "$DRAFT_BODY")
POST_ID=$(jq -er '.post.postId' <<<"$DRAFT")
VERSION=$(jq -er '.post.version' <<<"$DRAFT")

VALIDATION=$(curl --fail-with-body -sS -X POST -H "$AUTH" "$BASE/posts/$POST_ID/validate")
printf '%s\n' "$VALIDATION"
jq -e '.validation.valid == true' <<<"$VALIDATION" >/dev/null

# 202 means accepted. Keep this key for an identical retry after a timeout.
PUBLISH_KEY=$(new_key)
ACCEPTED=$(curl --fail-with-body -sS -X POST -H "$AUTH" \
  -H "Idempotency-Key: $PUBLISH_KEY" "$BASE/posts/$POST_ID/publish")
printf '%s\n' "$ACCEPTED"
curl --fail-with-body -sS -H "$AUTH" "$BASE/posts/$POST_ID"
```

For image/video destinations, [upload and finalize media](/docs/media) first,
then use the returned asset IDs in `mediaIds` and an eligible destination format.
Observe individual delivery IDs from the accepted response; use webhooks or a
bounded status poll with backoff. A single immediate status read may still be pending.

## Schedule instead of publish

Use this on a draft **instead of** the publish step above. Fetch its current
version again after any edit. This computes a future instant rather than using a
sample date that will expire.

```bash
SCHEDULED_AT=$(node -e 'console.log(new Date(Date.now()+86400000).toISOString())')
SCHEDULE_BODY=$(jq -n --arg at "$SCHEDULED_AT" --argjson version "$VERSION" \
  '{scheduledAt:$at,timezone:"America/Indiana/Indianapolis",expectedVersion:$version}')
SCHEDULE_KEY=$(new_key)
curl --fail-with-body -sS -X POST -H "$AUTH" -H "Idempotency-Key: $SCHEDULE_KEY" \
  -H "$JSON" "$BASE/posts/$POST_ID/schedule" -d "$SCHEDULE_BODY"
```

The instant must be future and within the **90-day horizon**; the UTC instant and
the display timezone are stored separately. If your API key expires at or before
that instant, the accepted response includes a `warnings` entry with code
`key_expires_before_schedule`. The delivery remains scheduled, but it must be
reviewed and resubmitted under an active principal before it can publish. The
same warning is preserved when replaying the request. Cancel while safely unclaimed:

```bash
curl -s -X POST -H "$AUTH" -H "Idempotency-Key: $(new_key)" $BASE/deliveries/$DELIVERY_ID/cancel
# Already submitted? → 409 too_late_to_cancel with the real state.
```

Retry **only** a known failed destination (unknown/successful are refused):

```bash
curl -s -X POST -H "$AUTH" -H "Idempotency-Key: $(new_key)" $BASE/deliveries/$DELIVERY_ID/retry
```

## Media (direct uploads)

Media bytes never pass through this API.

```bash
# 1. Reserve bytes → direct instructions (presigned PUT, or multipart for large files)
curl -s -X POST -H "$AUTH" -H "Idempotency-Key: $(new_key)" -H "$JSON" $BASE/media/upload-intents -d '{
  "filename": "poster.jpg", "declaredMime": "image/jpeg", "declaredBytes": 1048576 }'

# 2. Upload bytes DIRECTLY to the returned URL with the documented method.

# 3. Finalize: the server verifies size/signature on the immutable final copy.
#    Send ONLY the session identity (plus part receipts for multipart uploads)
#: bytes, MIME and checksum are observed server-side, never declared here.
curl -s -X POST -H "$AUTH" -H "Idempotency-Key: $(new_key)" -H "$JSON" $BASE/media/$ASSET_ID/finalize -d '{
  "sessionId": "…" }'

# multipart: include the ETag receipt of every uploaded part.
# Files at or above 50 MiB use multipart; use the returned part size and URLs.
# Upload every part and retain its ETag. Small files finalize with sessionId only.
# These are alternative finalization shapes, not two consecutive operations.
curl -s -X POST -H "$AUTH" -H "Idempotency-Key: $(new_key)" -H "$JSON" $BASE/media/$ASSET_ID/finalize -d '{
  "sessionId": "…",
  "multipart": { "parts": [ { "partNumber": 1, "etag": "…" } ] } }'

# 4. Status/expiry only: there is no permanent public media URL
curl -s -H "$AUTH" $BASE/media/$ASSET_ID
```

Files are temporary: scheduled posts keep their media through publishing, and a
dynamic `deleteAfter` (or null) is always shown. Keep your originals.

## Usage

`GET /usage` reports plan, connected/reserved account slots, members, storage,
the 90-day horizon and rate info. Activity numbers are operational metrics only:
**there is no remaining-post counter anywhere in the product**.

## Pagination

List endpoints use opaque cursors: `?limit=25&cursor=<nextCursor>`. Timestamps are
UTC ISO-8601. Continue until `nextCursor` is `null`; a filtered posts page can
be empty while its non-null cursor points to older records still to scan.
Prefer webhooks (see [webhooks](/docs/webhooks)) or bounded polling with backoff
over tight status loops.

## Limits and partial success

Destination capabilities (from `GET /capabilities`) carry the strictest
effective limits: app, provider, network and account. When a limit blocks a
request, the error envelope is actionable:

```json
{
  "error": {
    "code": "storage_limit",
    "message": "Active temporary media exceeds this plan's storage allowance.",
    "retryable": false,
    "requestId": "…"
  }
}
```

`account_limit`, `seat_limit`, `storage_limit`, `subscription_inactive` and
`trial_expired` are 402 responses; nothing is deleted, and drafts/queued work is
preserved for after an upgrade.

A publish/schedule is a batch of independent destination jobs. Partial success
is normal and reported per destination: never as an atomic promise:

```json
{
  "post": {
    "postId": "…",
    "version": 4,
    "status": "partially_published",
    "deliveries": [
      { "id": "…", "accountId": "…", "network": "instagram", "state": "published",
        "nativePostUrl": "https://instagram.com/p/…", "unresolvedExternalOutcome": false },
      { "id": "…", "accountId": "…", "network": "linkedin", "state": "reconnect_required",
        "nativePostUrl": null, "lastErrorCode": "reconnect_required" }
    ]
  },
  "requestId": "…"
}
```

Retry only the failed destination (`POST /deliveries/{id}/retry`); successful
destinations are never re-sent. Consent/reconnection requirements return
`requires_action` with safe instructions, never a secret.

## Full reference

For TikTok, `GET /accounts/{id}/tiktok/settings` returns the connected creator's
current privacy choices, interaction permissions, duration limit and publishing
mode availability. It requires `accounts:read` and honors the key allowlist.
Saving a draft or reading these settings does not supply consent.

A publish/schedule lacking current human confirmation returns HTTP 409
`consent_required` with `error.requiresAction.url` pointing to the saved draft
in the authenticated composer. Validation can return the same handoff alongside
its structured issues. The person reviews the exact video/caption and makes
explicit choices there; product keys and MCP cannot confirm on their behalf.
After a person confirms, retry through the normal shared publishing service.
Editing the content or changing the destination identity requires fresh review.
The handoff URL contains no product key, token or signed media URL and grants no
access to a person who lacks workspace membership. Its workspace UUID identifies
the key's workspace; a browser with a different selected workspace must explicitly
switch after a current membership check before reviewing this draft.

See [OpenAPI specification](/docs/openapi.yaml) for the complete, current contract. UI, REST
and MCP all read the same services, so they apply the same workspace rules. Results reflect each request’s
current state; separate requests can observe intervening updates.
