# AdExec REST API

> This Markdown file is the machine-readable source for the HTML page at <https://app.adexecai.shop/docs/api>. The page renders this exact file. All credentials below are placeholders; never commit or publish a real key.

**Base URL:** `https://app.adexecai.shop`

**Related:** [MCP documentation](https://app.adexecai.shop/docs/mcp.md) · [Machine-readable index](https://app.adexecai.shop/llms.txt)

## Surface overview

AdExec currently exposes two distinct authenticated surfaces:

| Surface | Used by | Credential | Canonical paths |
|---|---|---|---|
| External REST API | Server-to-server integrations | Organization API key sent as `Authorization: Bearer <key>` | `/api/v1/*` |
| Dashboard REST API | The AdExec web application | `HttpOnly` dashboard session cookie | `/api/orgs/{orgId}/*` |
| MCP | AI agents and MCP clients | OAuth 2.1 access token sent as `Authorization: Bearer <token>` | `https://mcp.adexecai.shop/mcp` |

MCP tokens, dashboard sessions, and organization API keys are separate credential domains and are not interchangeable.

## Authentication

### Organization API keys

Organization API keys are the machine-to-machine credential for the external `/api/v1/*` endpoints.

Create a key with a dashboard session:

```http
POST /api/orgs/{orgId}/api-keys
Content-Type: application/json

{
  "name": "Partner integration",
  "scopes": ["assets:write"],
  "expires_at": null
}
```

The full key is returned only once, in the creation response. Store it in a secret manager and send it on every external request:

```http
Authorization: Bearer $ADEXEC_ORG_API_KEY
```

Supported API-key scopes are exactly:

| Scope | Grants |
|---|---|
| `channels:read` | Read connected social channels |
| `channels:connect` | Start, poll, and sync social-channel connections |
| `assets:write` | Create, cancel, and finalize asset uploads |

Role ceilings apply in addition to the key's scopes. Owners and admins can create all three scopes; editors can create only `assets:write`; approvers and viewers cannot create keys.

List and revoke keys:

| Method | Path | Auth | Purpose |
|---|---|---|---|
| `GET` | `/api/orgs/{orgId}/api-keys` | Dashboard session, owner/admin | List safe key metadata |
| `POST` | `/api/orgs/{orgId}/api-keys` | Dashboard session, owner/admin | Create a key and return the secret once |
| `DELETE` | `/api/orgs/{orgId}/api-keys/{keyId}` | Dashboard session, owner/admin | Revoke a key immediately and idempotently |

### Dashboard session

The `/api/orgs/{orgId}/*` routes authenticate with the dashboard session cookie set by `POST /api/auth/login`. The organization ID in the URL is a selector over the caller's memberships; it is never trusted as an authorization claim.

State-changing dashboard requests must also present a trusted `Origin` or `Sec-Fetch-Site` header. Do not use a dashboard cookie as an external API credential.

### MCP OAuth

MCP uses OAuth 2.1 authorization-code flow with PKCE (`S256`). Access tokens are audience-bound to `https://mcp.adexecai.shop` and last 15 minutes. Refresh tokens rotate and are valid for 30 days; replaying a used refresh token revokes its whole token family.

See [MCP documentation](https://app.adexecai.shop/docs/mcp.md) for discovery, registration, authorization, and token endpoints.

## Response and error format

### API v1 envelope

The `/api/v1/*` routes and the upload/API-key routes return this envelope:

```json
{
  "code": 0,
  "data": {},
  "message": "",
  "correlation_id": "corr_01JEXAMPLE"
}
```

Errors keep the same top-level shape and add stable machine metadata under `data`:

```json
{
  "code": 1001,
  "data": {
    "error_code": "invalid_request",
    "retryable": false
  },
  "message": "Invalid upload declaration.",
  "correlation_id": "corr_01JEXAMPLE"
}
```

The response header `x-correlation-id` carries the same value. Rate-limit responses also include `Retry-After`, and may include `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset`.

### Dashboard envelope

Most read-only dashboard routes use the older envelope without a correlation ID:

```json
{
  "code": 0,
  "data": {},
  "message": ""
}
```

Their errors are `{"code":1001,"data":null,"message":"..."}` with an HTTP status mapped from the numeric code.

### Numeric response codes

| `code` | Typical HTTP status | Meaning |
|---|---|---|
| `0` | `200` / `201` | Success |
| `1001` | `400` / `413` / `415` / `422` | Invalid request or upload declaration |
| `1002` | `401` | Authentication failed |
| `1003` | `403` | Authorization or role failure |
| `1004` | `404` | Resource not found or outside the caller's scope |
| `2004` | `500` / `503` | Internal, storage, or finalize service failure |
| `3001` | `429` | Rate limited |
| `3002` | `409` | Conflict; an upload finalize may already be in progress |
| `4002` | `410` | Upload session expired |
| `4005` | `409` | Invalid state transition |

### Stable `error_code` values

| `error_code` | HTTP status | Meaning |
|---|---|---|
| `invalid_api_key` | `401` | Missing, malformed, expired, or revoked API key |
| `invalid_request` | `400` | Invalid JSON, fields, IDs, or request shape |
| `insufficient_scope` | `403` | API key lacks the required scope |
| `forbidden_role` | `403` | The acting member's role does not permit the action |
| `csrf_origin_rejected` | `403` | Dashboard mutation did not come from a trusted origin |
| `capability_disabled` | `403` | The capability is disabled for this workspace or deployment |
| `not_found` | `404` | Resource does not exist or is outside the caller's scope |
| `invalid_filename` | `400` | Filename is empty, too long, or contains unsafe characters |
| `invalid_byte_size` | `400` | `byte_size` is not a positive safe integer |
| `invalid_checksum` | `400` | Checksum is not 64 lowercase hexadecimal characters |
| `payload_too_large` | `413` | Declaration or uploaded object exceeds the configured limit |
| `unsupported_media_type` | `415` | Declared or detected media type is not supported |
| `length_mismatch` | `422` | Uploaded byte length differs from the declaration |
| `content_type_mismatch` | `422` | Uploaded content type differs from the declaration |
| `checksum_mismatch` | `422` | Uploaded checksum differs from the declaration |
| `object_missing` | `422` | Finalize could not find the uploaded object |
| `upload_expired` | `410` | Upload session exceeded its 30-minute lifetime |
| `upload_cancelled` | `409` | Upload was cancelled |
| `upload_failed` | `409` | Upload is no longer finalizable |
| `upload_in_progress` | `409` | Another finalize claim is active; retry later |
| `already_finalized` | `409` | Upload was already finalized |
| `rate_limited` | `429` | Request rate limit exceeded |
| `storage_unavailable` | `503` | Object storage is unavailable |
| `finalize_failed` | `503` | Finalize could not complete; the request is retryable |
| `internal_error` | `500` | Unclassified server failure |

## Asset uploads: three-step flow

### External API-key flow (recommended for integrations)

#### Step 1 — create the upload session

```http
POST /api/v1/assets/uploads
Authorization: Bearer $ADEXEC_ORG_API_KEY
Content-Type: application/json
```

```json
{
  "brand_id": "b1111111-1111-4111-8111-111111111111",
  "campaign_id": null,
  "filename": "reference.png",
  "content_type": "image/png",
  "byte_size": 12,
  "checksum_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
```

`brand_id` and `campaign_id` must be UUIDs visible to the API key. `campaign_id` is optional. `byte_size` must be a positive integer. `checksum_sha256` must be exactly 64 lowercase hexadecimal characters.

The response is `201` and contains a short-lived capability. Treat `upload_url` and `headers` as credentials:

```json
{
  "code": 0,
  "data": {
    "upload_id": "e1111111-1111-4111-8111-111111111111",
    "upload_url": "https://storage.example/upload-capability",
    "method": "PUT",
    "headers": {
      "Content-Type": "image/png",
      "If-None-Match": "*"
    },
    "expires_at": "2026-11-18T12:30:00.000Z"
  },
  "message": "",
  "correlation_id": "corr_01JEXAMPLE"
}
```

#### Step 2 — upload directly to the presigned URL

Send the file bytes to `data.upload_url` with `data.method` and **all** headers returned in `data.headers`. Do not add cookie authentication to the storage request.

```bash
curl --request PUT "$UPLOAD_URL" \
  --header 'Content-Type: image/png' \
  --header 'If-None-Match: *' \
  --data-binary @reference.png
```

The exact signed headers must match the response. If the response includes additional checksum or content-length headers, include those too.

#### Step 3 — finalize

```http
POST /api/v1/assets/uploads/{uploadId}/finalize
Authorization: Bearer $ADEXEC_ORG_API_KEY
```

No request body is required. The server verifies the object's size, content type, SHA-256 checksum, and file signature before creating the asset version.

```json
{
  "code": 0,
  "data": {
    "upload_id": "e1111111-1111-4111-8111-111111111111",
    "asset_id": "a1111111-1111-4111-8111-111111111111",
    "version_id": "f1111111-1111-4111-8111-111111111111",
    "type": "image",
    "status": "finalized",
    "replayed": false
  },
  "message": "",
  "correlation_id": "corr_01JEXAMPLE"
}
```

Finalize is idempotent. A retry after success returns `replayed: true` with the original asset and version IDs.

#### Cancel an upload

```http
DELETE /api/v1/assets/uploads/{uploadId}
Authorization: Bearer $ADEXEC_ORG_API_KEY
```

Returns `200` when object cleanup is complete or `202` when cleanup is still pending. Cancelling an already finalized upload returns `already_finalized`.

#### Curl example: create, upload, and finalize

```bash
TOKEN='<ORG_API_KEY>'
BRAND_ID='<BRAND_UUID>'
FILE='reference.png'
CHECKSUM="$(sha256sum "$FILE" | awk '{print $1}')"
SIZE="$(wc -c < "$FILE" | tr -d ' ')"

SESSION="$(curl -sS https://app.adexecai.shop/api/v1/assets/uploads \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  --data "{\"brand_id\":\"$BRAND_ID\",\"filename\":\"reference.png\",\"content_type\":\"image/png\",\"byte_size\":$SIZE,\"checksum_sha256\":\"$CHECKSUM\"}")"

UPLOAD_ID="$(printf '%s' "$SESSION" | jq -r '.data.upload_id')"
UPLOAD_URL="$(printf '%s' "$SESSION" | jq -r '.data.upload_url')"

curl -sS --request PUT "$UPLOAD_URL" \
  -H 'Content-Type: image/png' \
  -H 'If-None-Match: *' \
  --data-binary "@$FILE"

curl -sS --request POST \
  "https://app.adexecai.shop/api/v1/assets/uploads/$UPLOAD_ID/finalize" \
  -H "Authorization: Bearer $TOKEN"
```

### Dashboard session flow

The web application uses equivalent organization-scoped routes:

| Method | Path | Purpose |
|---|---|---|
| `POST` | `/api/orgs/{orgId}/assets/uploads` | Create an upload session |
| `DELETE` | `/api/orgs/{orgId}/assets/uploads/{uploadId}` | Cancel an upload |
| `POST` | `/api/orgs/{orgId}/assets/uploads/{uploadId}/finalize` | Finalize an upload |

These routes require the dashboard session cookie plus `Origin` or `Sec-Fetch-Site` validation. Owner, admin, and editor roles may upload. The step 2 presigned `PUT` is identical to the external flow.

### Upload policy

| Item | Limit |
|---|---|
| Maximum upload declaration body | 4 KiB |
| Upload-session lifetime | 30 minutes |
| Image types | `image/png`, `image/jpeg`, `image/webp`, `image/gif` |
| Image maximum size | 26,214,400 bytes (25 MiB) |
| Video types | `video/mp4`, `video/webm`, `video/quicktime` |
| Video maximum size | 262,144,000 bytes (250 MiB) |
| Rate limit | 30 sessions per organization per hour and 10 per actor per hour |

## Channels: external API

All channel routes use an organization API key. Read routes require `channels:read`; connection and sync routes require `channels:connect`.

| Method | Path | Purpose |
|---|---|---|
| `GET` | `/api/v1/channels?brand_id={brandId}` | List connected channels; `brand_id` is optional |
| `POST` | `/api/v1/channels/connect` | Start a connection session, or deny one with `action: "deny"` |
| `GET` | `/api/v1/channels/connect/{sessionId}` | Poll a connection session |
| `POST` | `/api/v1/channels/sync` | Sync channels for a brand |

Connectable platforms are `instagram`, `facebook`, `x`, `linkedin`, `youtube`, and `tiktok`.

Start a connection:

```json
{
  "brand_id": "b1111111-1111-4111-8111-111111111111",
  "platform": "instagram"
}
```

Deny a pending connection:

```json
{
  "action": "deny",
  "session_id": "c1111111-1111-4111-8111-111111111111"
}
```

## Assets and credits: dashboard API

| Method | Path | Purpose |
|---|---|---|
| `GET` | `/api/orgs/{orgId}/assets?brand_id={brandId}&campaign_id={campaignId}&type=image\|video&limit=25` | Search asset metadata |
| `GET` | `/api/orgs/{orgId}/assets/{assetId}/delivery?variant=original\|preview\|thumbnail` | Mint a short-lived signed delivery URL |
| `GET` | `/api/orgs/{orgId}/credits?limit=50` | Read credit balance and recent ledger entries |

The credits response exposes `available`, `reserved`, `lifetime_granted`, `lifetime_consumed`, and `ledger`. There is no `/api/v1` credit endpoint in the current repository.

## Job diagnostics

`GET /api/v1/jobs/{jobId}` returns the current state of one publishing job or generation job. It requires the `channels:read` API-key scope, because it is the read side of publishing. The job must belong to the key's organization and to a brand the key can see; anything else is a `404`.

| Method | Path | Auth | Purpose |
|---|---|---|---|
| `GET` | `/api/v1/jobs/{jobId}` | Organization API key, `channels:read` | Read job status and a safe failure reason |

```http
GET /api/v1/jobs/11111111-1111-4111-8111-111111111111
Authorization: Bearer $ADEXEC_ORG_API_KEY
```

A publishing job returns `job_type: "publishing"`, a generation job returns `job_type: "creative.generate_image"` (or `creative.generate_video`), and both include an `error` object:

```json
{
  "code": 0,
  "data": {
    "job_id": "11111111-1111-4111-8111-111111111111",
    "job_type": "publishing",
    "status": "failed",
    "provider_state": "definitive_failed",
    "error": {
      "code": "publishing_account_not_configured",
      "message": "Publishing is not configured for this workspace. Contact support.",
      "retryable": false
    },
    "created_at": "2026-11-18T11:00:00.000Z",
    "updated_at": "2026-11-18T11:00:10.000Z",
    "completed_at": "2026-11-18T11:00:10.000Z",
    "correlation_id": "corr_01JEXAMPLE"
  },
  "message": "",
  "correlation_id": "corr_01JEXAMPLE"
}
```

`error` is `null` while the job has no recorded failure. When it is present:

| Field | Meaning |
|---|---|
| `code` | Stable, allowlisted failure code such as `publishing_account_not_configured`, `policy_violation`, or `budget_exceeded` |
| `message` | Fixed, vendor-free sentence derived from `code` |
| `retryable` | `true` when retrying the same request after a short wait is reasonable |

The message is derived from the persisted code. Stored provider text is never returned. `provider_state` is present for publishing jobs and distinguishes `definitive_failed` (safe to retry after fixing the cause) from `reconciliation_required` (the provider may have accepted the post, so a human must reconcile before retrying).

An unknown, malformed, or out-of-scope job id returns the standard envelope with HTTP `404`:

```json
{
  "code": 1004,
  "data": {
    "error_code": "not_found",
    "retryable": false
  },
  "message": "Job not found.",
  "correlation_id": "corr_01JEXAMPLE"
}
```

Unimplemented `/api/v1/*` paths also answer with a JSON envelope (`code: 1004`, `error_code: "not_found"`) instead of an HTML error page.

## Generation jobs and usage quotes

Generation jobs are created through MCP tools. This is intentional: the MCP gateway performs scope, brand, workspace, price, affordability, idempotency, and durable-queue checks before creating a job. Reading a job is available both through `creative.get_generation_status` and through `GET /api/v1/jobs/{jobId}`.

| Step | MCP tool | Result |
|---|---|---|
| Quote first | `usage.get_quote` | Credits required for an operation |
| Generate image | `creative.generate_image` or `creative.agnes_image` | Durable generation-job handle |
| Generate video | `creative.generate_video` | Durable generation-job handle |
| Check job | `creative.get_generation_status` | Current job status and safe error code |
| Read balance | `usage.get_balance` | Available, reserved, granted, and consumed credits |

A generation tool returns a job handle:

```json
{
  "job_id": "11111111-1111-4111-8111-111111111111",
  "capability": "image",
  "status": "queued",
  "credits_quoted": "10",
  "correlation_id": "corr_01JEXAMPLE"
}
```

`creative.get_generation_status` returns:

```json
{
  "job_id": "11111111-1111-4111-8111-111111111111",
  "job_type": "creative.generate_image",
  "status": "running",
  "error_code": null,
  "error": null,
  "created_at": "2026-11-18T11:00:00.000Z",
  "updated_at": "2026-11-18T11:00:10.000Z",
  "correlation_id": "corr_01JEXAMPLE"
}
```

When the job failed, `error` carries the same `{code, message, retryable}` object as `GET /api/v1/jobs/{jobId}`. `error_code` is kept for clients that already read it.

Stored generation statuses are `queued`, `running`, `waiting_provider`, `waiting_approval`, `succeeded`, `failed`, `cancelled`, and `expired`.

`usage.get_quote` accepts `operation` plus optional `parameters`:

| `operation` | Billable capability | Relevant parameters |
|---|---|---|
| `creative.generate_image` | `image` | — |
| `creative.agnes_image` | `image` | — |
| `creative.generate_video` | `video` or `video_premium` | `quality`: `standard` or `premium` |
| `publishing.request_schedule` | `publishing` | — |

Example quote call over MCP:

```bash
curl -sS https://mcp.adexecai.shop/mcp \
  -H "Authorization: Bearer $ADEXEC_MCP_ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"usage.get_quote","arguments":{"operation":"creative.generate_video","parameters":{"quality":"premium"}}}}'
```

Quote response content includes `operation`, `capability`, `unit: "credits"`, `credits`, and `correlation_id`.

## Related documentation

- [MCP endpoint, OAuth, tools, and schemas](https://app.adexecai.shop/docs/mcp.md)
- [Human-readable MCP documentation](https://app.adexecai.shop/docs/mcp)
- [AI-readable documentation index](https://app.adexecai.shop/llms.txt)
