Skip to content

API reference

Generate images, video, audio and 3D models, upscale and edit with the same models as the Loupe app, from your own code. Everything is plain HTTPS + JSON: create a generation, then poll it — or receive a signed webhook — until its outputs are ready.

Base URL
/api/v1
Authentication
Bearer lp_…
Format
JSON, snake_case
On this page

Quick start

  1. A workspace owner or admin creates an API key in Settings → API keys. The key (lp_…) is shown once.
  2. Point your shell at your deployment and key:
    shell
    # Your deployment's origin, and an API key from Settings → API keys
    export LOUPE_BASE_URL="https://loupe.example.com"
    export LOUPE_API_KEY="lp_…"
  3. Start a generation. The response is 202 Accepted with the new generation:
    curl
    curl -X POST "$LOUPE_BASE_URL/api/v1/generations" \
      -H "Authorization: Bearer $LOUPE_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: lighthouse-0001" \
      -d '{
        "model": "nano-banana-2.1",
        "input": {
          "prompt": "a lighthouse on a cliff at dawn, soft fog",
          "aspect_ratio": "16:9"
        },
        "webhook_url": "https://example.com/hooks/loupe"
      }'
    202 response
    {
      "id": "job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f",
      "object": "generation",
      "model": "nano-banana-2.1",
      "tool": "image",
      "status": "queued",
      "input": {
        "prompt": "a lighthouse on a cliff at dawn, soft fog",
        "aspect_ratio": "16:9",
        "resolution": "1K",
        "num_images": 1
      },
      "credits_cost": 15,
      "error": null,
      "outputs": [],
      "created_at": "2026-11-07T10:15:02.114Z",
      "completed_at": null
    }
  4. Poll GET /api/v1/generations/{id} every 2–5 seconds until status is succeeded, failed or canceled — or pass a webhook_url and get notified (webhooks).
  5. Download each outputs[].url. Output URLs are signed and valid for 6 hours; fetch the generation again for fresh ones.

Basics

Base URL

https://<your Loupe domain>/api/v1. The examples use the shell variables LOUPE_BASE_URL (your deployment's origin, no trailing slash) and LOUPE_API_KEY.

Authentication

Send your key in the Authorization header: Authorization: Bearer lp_….

  • Keys belong to a workspace. Everything a key does — generations, uploads, credits — happens in that workspace and is paid from its credits. Workspace owners and admins create and revoke keys in Settings → API keys; a revoked key stops working immediately.
  • Keep keys on your server. The API does not allow browser (CORS) requests.
  • A missing, malformed, unknown or revoked key answers 401 unauthorized with WWW-Authenticate: Bearer.

Requests and responses

  • Bodies are JSON (Content-Type: application/json, at most 1 MiB) with snake_case keys. Unknown fields are rejected with 422, so typos never pass silently.
  • Timestamps are ISO 8601 in UTC with milliseconds (2026-11-07T10:15:02.114Z). Ids carry a prefix: job_… (generations), ast_… (assets), whd_… (webhook events).
  • Responses are never cached (Cache-Control: no-store). New fields may be added to responses over time; ignore fields you do not know.
  • Each endpoint supports only the methods documented for it, plus HEAD where it supports GET. A GET, HEAD, POST, PUT, PATCH or DELETE request to an endpoint that does not support that method answers 405 method_not_allowed, with an Allow header listing the methods it supports; OPTIONS answers 204 with the same header.
  • An unknown path under /api/v1 answers 404 not_found in the same error format.

Errors

Every error has the same shape:

422 response
{
  "error": {
    "code": "validation_error",
    "message": "Invalid input",
    "details": {
      "issues": [
        {
          "path": "input.prompt",
          "message": "Prompt is required"
        }
      ]
    }
  }
}

Branch on code (stable); message is human-readable and may change. details is present when listed below.

StatuscodeMeaningdetails
400bad_requestMalformed JSON or an invalid cursor.—
400content_policyThe prompt was refused by the content policy.—
401unauthorizedMissing, invalid or revoked API key.—
402insufficient_creditsThe workspace does not have enough credits.{ required, available }
403forbiddenThe request came from a web page of another origin (MCP endpoint).—
404not_foundUnknown id — or one that belongs to another workspace — or unknown endpoint.—
405method_not_allowedThe endpoint does not support this HTTP method; the Allow header lists the ones it does.—
409conflictThe request conflicts with the current state (see each endpoint).—
413payload_too_largeThe body or the file is too large.{ max_bytes }
415unsupported_media_typeThe body is not JSON, or the file type is not allowed.—
422validation_errorInvalid parameters.{ issues: [{ path, message }] }
429rate_limitedToo many requests; wait Retry-After seconds.{ retry_after_sec }
429concurrency_limitToo many generations running at once.{ limit }
500internalUnexpected error. Retry later.—
502provider_errorThe model provider refused or failed the request. Nothing was charged; retry.—
503model_unavailableThe model is not available right now.{ model_id }

Validation issue paths name what was wrong: a body field (model, webhook_url, size, …), a model input (input.prompt, input.images.1, or input for the object itself), the Idempotency-Key header, or "" for the body itself (for example an unknown field).

Rate limits

LimitScopeWhen exceeded
120 requests per minuteper API key, all endpoints together429 rate_limited + Retry-After
30 new generations per minuteper API key429 rate_limited + Retry-After
60 new uploads per minute, and as many completionsper API key429 rate_limited + Retry-After
2 (Free), 4 (Starter), 8 (Pro) or 16 (Studio) generations running at onceper workspace (app and API together)429 concurrency_limit
20 prompt-tool requests per minuteper API key429 rate_limited + Retry-After
300 prompt-tool requests per rolling 24 hoursper workspace (app and API together)429 rate_limited + Retry-After

Windows are rolling (the last 60 seconds; the last 24 hours for the daily prompt-tool allowance). Running means pending, queued or processing; when a workspace is at its limit, retry after one of its generations finishes. Requests with an invalid key do not count against any key.

Idempotency

Send an Idempotency-Key header (1–128 visible ASCII characters, e.g. a UUID) with POST /api/v1/generations to retry safely after a timeout or a network error:

  • The first request with a key creates the generation. Any later request with the same key in the same workspace returns that generation (202) instead of creating another one — even if both arrive at the same time. Only the model is compared: a different input does not create a new generation.
  • Reusing a key with a different model answers 409 conflict.
  • Every request is still validated and rate-limited before the key is looked up, so a retry must be a valid request too.
  • If the original generation failed (for example with 502 provider_error), retries with its key return it as failed: use a new key to try again.
  • Keys are scoped to the workspace (every key of the workspace shares them) and do not expire.

Pagination

GET /api/v1/generations returns the newest items first as { "items": [...], "next_cursor": "…" }. Pass next_cursor as the cursor query parameter to get the next page; null means there are no more. limit is 1–100 (default 24).

Credits

  • Every generation has a price in credits, credits_cost, fixed when it is created. Those credits are held while it runs, charged when it succeeds, and released when it fails or is canceled. Without enough credits, creating it answers 402 insufficient_credits.
  • Plans that include "unlimited" models apply them in the Loupe app only: API generations are always charged.
  • A model's base_credits is its price at default settings (with a 1024×1024 image, a 5-second 1280×720 video or a 10-second audio input where it takes one, and as many such videos as a videos field needs at least). Resolution, duration, number of outputs and input sizes change the price.
  • GET /api/v1/credits returns the balance (credit balance).

Models

List models

GET/api/v1/models

The models available right now, in catalog order. Every request needs the Authorization header with your API key.

QueryTypeDescription
toolstringOnly models of this tool.
curl
curl "$LOUPE_BASE_URL/api/v1/models?tool=image" \
  -H "Authorization: Bearer $LOUPE_API_KEY"

Response: { "items": [Model, …] } (see the model object below).

Get a model

GET/api/v1/models/{id}

One model, with the definitions of its inputs. 404 for an unknown id; 503 model_unavailable for a model that exists but is not offered right now.

curl
curl "$LOUPE_BASE_URL/api/v1/models/nano-banana-2.1" \
  -H "Authorization: Bearer $LOUPE_API_KEY"
200 response
{
  "id": "nano-banana-2.1",
  "object": "model",
  "name": "Nano Banana 2.1",
  "vendor": "Google",
  "family": "Nano Banana",
  "description": "Google's newest image model: precise prompt following, legible text and up to 14 reference images.",
  "tool": "image",
  "mode": null,
  "output_type": "image",
  "tags": [
    "new",
    "hd"
  ],
  "is_default": true,
  "estimated_seconds": 20,
  "base_credits": 15,
  "pricing_note": "Token-billed, per image: about $0.040 at 1K, $0.059 at 2K or $0.133 at 4K for the image, plus about $0.018 reserved for thinking, $0.002 per reference image and $1.764 per million prompt tokens.",
  "fields": [
    {
      "key": "prompt",
      "label": "Prompt",
      "description": null,
      "type": "prompt",
      "required": true,
      "max_length": 4000,
      "min_length": 3
    },
    {
      "key": "images",
      "label": "Reference images",
      "description": "Optional: up to 14 images that guide the subject, style or composition.",
      "type": "images",
      "required": false,
      "min_items": 0,
      "max_items": 14
    },
    {
      "key": "aspect_ratio",
      "label": "Aspect ratio",
      "description": null,
      "type": "aspect-ratio",
      "required": false,
      "options": [
        "auto",
        "1:1",
        "4:3",
        "3:4",
        "3:2",
        "2:3",
        "16:9",
        "9:16",
        "5:4",
        "4:5",
        "21:9",
        "4:1",
        "1:4",
        "8:1",
        "1:8"
      ],
      "default": "auto"
    },
    {
      "key": "resolution",
      "label": "Resolution",
      "description": null,
      "type": "select",
      "required": false,
      "options": [
        {
          "value": "1K",
          "label": "1K",
          "description": null
        },
        {
          "value": "2K",
          "label": "2K",
          "description": null
        },
        {
          "value": "4K",
          "label": "4K",
          "description": null
        }
      ],
      "default": "1K"
    },
    {
      "key": "num_images",
      "label": "Images",
      "description": null,
      "type": "slider",
      "required": false,
      "min": 1,
      "max": 4,
      "step": 1,
      "default": 1
    },
    {
      "key": "seed",
      "label": "Seed",
      "description": null,
      "type": "seed",
      "required": false,
      "min": 0,
      "max": 2147483647
    }
  ],
  "presets": []
}

The model object

FieldTypeDescription
idstringPass it as model when creating a generation.
object"model"
name, vendor, family, descriptionstring
toolstringThe tool it belongs to.
modestring or nullt2v / i2v (text- or image-to-video) for video models, creative / precision for upscalers, i3d / t3d (image- or text-to-3D) for 3D models.
output_typestringimage, video, audio or model (a 3D model: one GLB file).
tagsstring[]Labels such as new, fast, pro, audio, hd.
is_defaultbooleanThe model the app selects by default for its tool (and mode).
estimated_secondsintegerTypical generation time at default settings.
base_creditsintegerPrice at default settings.
pricing_notestringHow the model provider prices it.
fieldsField[]Its inputs (field definitions below).
presetsobject[]Named sets of input values: { id, label, values }.

Field definitions

input is an object keyed by field key. Every field definition has key, type, label, description (string or null) and required (true when the field must be sent; fields with a default are never required). Values are checked strictly: unknown keys are rejected, strings are trimmed, and an omitted optional field gets its default where it has one.

typeValue in inputExtra keys
promptstring, min_length–max_length charactersmax_length, min_length (or null)
textstring, at most max_length charactersmax_length
selectone of options[].valueoptions ({ value, label, description }), default
aspect-ratioone of options ("W:H" or "auto")options, default
slidernumber from min to max on the step gridmin, max, step, default
numbernumber from min to max (whole when integer)min, max, step, integer, default (or null)
togglebooleandefault
seedinteger from min to maxmin (0), max (2147483647)
image, video, audioone asset of that kind—
imagesarray of image assets, no duplicatesmin_items, max_items
videosarray of video assets in playing order; one video may appear more than oncemin_items, max_items
maskone image: a black-and-white PNG the size of the image in field image_key; white marks the area to changeimage_key

A list (images, videos) holds min_items to max_items entries. One that is not required may be left out or sent empty; with any entries it still needs at least min_items.

An asset value is either the id of an asset of your workspace (ast_…, from an upload or a previous generation's outputs[].id) or a public https:// URL (at most 2048 characters, no credentials) that the model provider can download. Models that need an input's size or duration — to compute their price or to check it against their limits — accept only asset ids for that field (422 for a URL), and so do the start and end frames of every image-to-video model. 3D models (model assets) are outputs only: no field accepts one (422).

Tools

toolNameWhat it doesOutput
imageImage generatorCreate images from a prompt with the leading image models.image
videoVideo generatorTurn a prompt or a still image into a video clip.video
motionMotion transferMake the character in a photo copy the moves of a reference video.video
motion-graphicsMotion graphicsDescribe animated text, shapes and logos, or rebuild a clip; the animation is made as code and rendered to video.video
vectorVectorCreate scalable SVG icons, logos and illustrations from a prompt.image
sketchSketch to imageDraw a rough sketch and turn it into a finished image.image
transparentTransparent PNGGenerate stickers, logos and design elements on a transparent background.image
3d3D generatorTurn a photo or a prompt into a textured 3D model you can rotate and download as GLB.model
panorama360° panoramaCreate a 360° panorama from a prompt or a photo, and look around it.image
upscaleUpscalerEnlarge images up to 16× with invented or faithful detail.image
video-upscaleVideo upscalerSharpen and enlarge video while keeping motion natural.video
editImage editorChange an image by describing the edit, with optional references.image
inpaintRetouchPaint over an area and describe what should replace it.image
expandExpandExtend an image beyond its borders to a new aspect ratio.image
remove-bgRemove backgroundCut out the subject onto a transparent background.image
backgroundNew backgroundKeep the subject and generate a new background or a product scene around it.image
relightRelightChange the lighting of a photo after it was taken.image
reimagineReimagineGenerate fresh takes on an image or restyle it.image
cameraCamera angleMove the camera around the subject of a single photo.image
variationsVariationsTurn one image into a consistent grid of new angles, moments, expressions or ages.image
vectorizeVectorizeTrace an image into a clean, scalable SVG.image
layersSplit into layersTake an image apart into a background and transparent layers, with any text read out.image
mockupMockupsPut a logo or artwork on apparel, devices, print and packaging, or on your own photo.image
skinSkin retouchClear blemishes and even out skin in portraits while keeping texture.image
video-editVideo editorChange a clip by describing the edit: restyle it, swap the setting, add or remove things.video
video-extendExtend videoContinue a clip with new seconds that follow its motion and look.video
video-remove-bgRemove video backgroundCut the subject out of every frame, onto transparency or a solid colour.video
video-relightVideo relightChange the direction and colour of the light in a clip.video
swapCharacter swapReplace the person in a clip with your own character, keeping every move.video
talkTalking videoType a script and the person in your clip says it, with synced lips.video
lipsyncLip syncMake a face in a video or photo speak any audio track.video
video-toolsVideo toolsTrim, resize, join, add a soundtrack, smooth motion or slow it down, and convert to HDR.video
ttsVoiceTurn text into natural speech.audio
sfxSound effectsGenerate sound effects from a description or a video.audio
musicMusicCompose original music from a prompt.audio
isolateIsolate voiceStrip music and background noise to keep only the voice.audio

Generations

Create a generation

POST/api/v1/generations

Answers 202 Accepted with the generation and a Location: /api/v1/generations/{id} header.

Body fieldTypeDescription
modelstring, requiredA model id.
inputobject, requiredThe model’s inputs, keyed by field.
webhook_urlstring or nullA public https:// URL to notify when the generation finishes.
HeaderDescription
Idempotency-KeyOptional (see idempotency).
curl
curl -X POST "$LOUPE_BASE_URL/api/v1/generations" \
  -H "Authorization: Bearer $LOUPE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: lighthouse-0001" \
  -d '{
    "model": "nano-banana-2.1",
    "input": {
      "prompt": "a lighthouse on a cliff at dawn, soft fog",
      "aspect_ratio": "16:9"
    },
    "webhook_url": "https://example.com/hooks/loupe"
  }'
202 response
{
  "id": "job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f",
  "object": "generation",
  "model": "nano-banana-2.1",
  "tool": "image",
  "status": "queued",
  "input": {
    "prompt": "a lighthouse on a cliff at dawn, soft fog",
    "aspect_ratio": "16:9",
    "resolution": "1K",
    "num_images": 1
  },
  "credits_cost": 15,
  "error": null,
  "outputs": [],
  "created_at": "2026-11-07T10:15:02.114Z",
  "completed_at": null
}

The generation in the response is usually queued, but it can already be further along: finalizing or succeeded when the model answered before the request returned, or failed / canceled when a cancel or a timeout won the race with the submission (its credits are released and nothing is charged). Always read status.

input in the response is normalised: strings trimmed and defaults filled in. To use your own files, pass asset ids or URLs in asset fields:

curl
curl -X POST "$LOUPE_BASE_URL/api/v1/generations" \
  -H "Authorization: Bearer $LOUPE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nano-banana-2.1-edit",
    "input": {
      "prompt": "make the jacket deep red",
      "images": [
        "ast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c",
        "https://example.com/fabric-swatch.jpg"
      ]
    }
  }'

Errors: 402 insufficient_credits, 400 content_policy, 422 validation_error, 409 conflict (idempotency key reused with another model), 429 rate_limited / concurrency_limit, 502 provider_error (the generation exists as failed and nothing is charged), 503 model_unavailable.

List generations

GET/api/v1/generations

The workspace's generations (made with the app or the API), newest first.

QueryTypeDescription
statusstringOnly this status.
toolstringOnly this tool.
limitinteger1–100, default 24.
cursorstringnext_cursor of the previous page.
curl
curl "$LOUPE_BASE_URL/api/v1/generations?status=succeeded&limit=10" \
  -H "Authorization: Bearer $LOUPE_API_KEY"
200 response
{
  "items": [
    {
      "id": "job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f",
      "object": "generation",
      "model": "nano-banana-2.1",
      "tool": "image",
      "status": "succeeded",
      "input": {
        "prompt": "a lighthouse on a cliff at dawn, soft fog",
        "aspect_ratio": "16:9",
        "resolution": "1K",
        "num_images": 1
      },
      "credits_cost": 15,
      "error": null,
      "outputs": [
        {
          "id": "ast_3a9d6f1c2b7e4d5a8c0b1e2f3a4b5c6d",
          "type": "image",
          "mime_type": "image/png",
          "url": "https://loupe.example.com/api/files/ws/ws_4c1d8e2f9a3b4c5d6e7f8091a2b3c4d5/gen/job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f/0.png?exp=1794067324&sig=5d0c…",
          "width": 1344,
          "height": 768,
          "duration_ms": null
        }
      ],
      "created_at": "2026-11-07T10:15:02.114Z",
      "completed_at": "2026-11-07T10:15:24.870Z"
    }
  ],
  "next_cursor": "eyJ0IjoiMjAyNi0xMS0wN1QxMDoxNTowMi4xMTRaIiwiaWQiOiJqb2JfMGY4YzJlM2Q2YjRhNGIwZTljMWQyYTNiNGM1ZDZlN2YifQ"
}

Get a generation

GET/api/v1/generations/{id}

The generation's current state. While it runs, this request also asks the model provider for progress whenever a check is due, so polling every 2–5 seconds is fine. 404 when the id is unknown or belongs to another workspace.

curl
curl "$LOUPE_BASE_URL/api/v1/generations/job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f" \
  -H "Authorization: Bearer $LOUPE_API_KEY"
200 response
{
  "id": "job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f",
  "object": "generation",
  "model": "nano-banana-2.1",
  "tool": "image",
  "status": "succeeded",
  "input": {
    "prompt": "a lighthouse on a cliff at dawn, soft fog",
    "aspect_ratio": "16:9",
    "resolution": "1K",
    "num_images": 1
  },
  "credits_cost": 15,
  "error": null,
  "outputs": [
    {
      "id": "ast_3a9d6f1c2b7e4d5a8c0b1e2f3a4b5c6d",
      "type": "image",
      "mime_type": "image/png",
      "url": "https://loupe.example.com/api/files/ws/ws_4c1d8e2f9a3b4c5d6e7f8091a2b3c4d5/gen/job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f/0.png?exp=1794067324&sig=5d0c…",
      "width": 1344,
      "height": 768,
      "duration_ms": null
    }
  ],
  "created_at": "2026-11-07T10:15:02.114Z",
  "completed_at": "2026-11-07T10:15:24.870Z"
}

Cancel a generation

POST/api/v1/generations/{id}/cancel

Answers the generation with status canceled; its credits are released. Only pending and queued generations can be canceled: 409 conflict once it started or finished; 502 provider_error when the provider could not be reached (retry).

curl
curl -X POST "$LOUPE_BASE_URL/api/v1/generations/job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f/cancel" \
  -H "Authorization: Bearer $LOUPE_API_KEY"

The generation object

FieldTypeDescription
idstringjob_…
object"generation"
modelstringThe model id.
toolstringThe model’s tool.
statusstringSee statuses.
inputobjectThe normalised input.
credits_costintegerIts price; held while it runs, charged on success, released on failure or cancellation (the value stays).
errorobject or null{ code, message } when it failed.
outputsobject[]The results in order, once it succeeded.
created_atstring
completed_atstring or nullWhen it reached a final status.

Each output: id (an asset id — use it as an input or with GET /api/v1/assets/{id}), type (image, video, audio, model), mime_type, url (signed, valid 6 hours), width and height (null for audio and 3D models), duration_ms (null for images and 3D models).

For example, a failed generation has "status": "failed", no outputs, and an error such as:

error
{
  "code": "timeout",
  "message": "The job took too long and was stopped."
}

Error codes include timeout, provider_error, submit_failed, provider_lost, bad_output, no_output, output_too_large, finalize_failed, model_unavailable and codes reported by the model provider (for example provider_validation); message is safe to show to your users.

Statuses

statusMeaning
pendingAccepted; being sent to the model provider.
queuedWaiting at the model provider.
processingRunning.
finalizingDone at the provider; the outputs are being saved (usually a second or two).
succeededFinal. Outputs are ready; the credits were charged.
failedFinal. See error; the credits were released.
canceledFinal. Canceled before it started; the credits were released.

Uploads and assets

Upload a file

POST/api/v1/uploads

Uploading takes three requests: create the upload, PUT the bytes, complete it.

1. Create the upload — answers 201 with where to send the file.

Body fieldTypeDescription
filenamestringThe original file name (at most 1024 characters; may be empty).
content_typestringThe file’s type (see the table below).
sizeintegerThe file’s exact size in bytes.
purposestringOptional: content (the default) or mask (see masks).
curl
curl -X POST "$LOUPE_BASE_URL/api/v1/uploads" \
  -H "Authorization: Bearer $LOUPE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "filename": "portrait.jpg",
    "content_type": "image/jpeg",
    "size": 2483021
  }'
201 response
{
  "asset_id": "ast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c",
  "upload": {
    "url": "https://loupe.example.com/api/uploads/content?key=tmp%2Fuploads%2Fast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c.jpg&exp=1794046802&max=2483021&ct=image%2Fjpeg&sig=0b4e…",
    "method": "PUT",
    "headers": {
      "Content-Type": "image/jpeg"
    }
  }
}

2. PUT the bytes to upload.url with exactly upload.headers and without your API key, within 15 minutes. Send exactly size bytes; a larger body may be refused. The file itself is checked when you complete the upload.

curl
# upload.url and upload.headers from the previous response (no API key here)
curl -X PUT "$UPLOAD_URL" \
  -H "Content-Type: image/jpeg" \
  --data-binary @portrait.jpg

3. Complete it with POST /api/v1/uploads/{asset_id}/complete, which answers the asset. The content is checked: its actual type must be an allowed type of the same kind as declared (415 otherwise), no larger than the declared size and the size limits (413) and, for images, within the dimension limits (422). Completing again returns the same asset; completing before the PUT answers 409 conflict. While the server is busy verifying other large uploads it may answer 429 rate_limited with Retry-After: complete again after that delay (the uploaded file is kept, so no new PUT is needed). Uploads not completed within 24 hours are deleted.

curl
curl -X POST "$LOUPE_BASE_URL/api/v1/uploads/ast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c/complete" \
  -H "Authorization: Bearer $LOUPE_API_KEY"
200 response
{
  "id": "ast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c",
  "object": "asset",
  "type": "image",
  "source": "upload",
  "mime_type": "image/jpeg",
  "filename": "portrait.jpg",
  "bytes": 2483021,
  "width": 3024,
  "height": 4032,
  "duration_ms": null,
  "url": "https://loupe.example.com/api/files/ws/ws_4c1d8e2f9a3b4c5d6e7f8091a2b3c4d5/up/ast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c.jpg?exp=1794067324&sig=a71f…",
  "thumbnail_url": "https://loupe.example.com/api/files/ws/ws_4c1d8e2f9a3b4c5d6e7f8091a2b3c4d5/thumb/ast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c.webp?exp=1794067324&sig=c3d9…",
  "download_url": "https://loupe.example.com/api/files/ws/ws_4c1d8e2f9a3b4c5d6e7f8091a2b3c4d5/up/ast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c.jpg?exp=1794067324&dl=portrait.jpg&sig=e80b…",
  "generation_id": null,
  "created_at": "2026-11-07T10:20:41.302Z",
  "deleted_at": null
}
Kindcontent_typeLimits
Imageimage/png, image/jpeg, image/webp30 MiB; at most 16,384 px per side and 100 megapixels
Videovideo/mp4, video/quicktime500 MiB
Audioaudio/mpeg, audio/wav, audio/mp4, audio/ogg, audio/flac100 MiB

SVG, GLB (3D models are outputs only), HTML and other types are never accepted. Creating and completing uploads are each limited to 60 requests per minute per key.

Masks

Upload an image with "purpose": "mask" when it only serves as an input of a generation, such as the mask field of an inpainting model. A mask must be a PNG, JPEG or WebP image (422 with an issue on purpose otherwise). It is completed and used like any other upload, but it never appears in the workspace’s library, and it is deleted 7 days after it was uploaded unless a generation that is still running uses it.

Get an asset

GET/api/v1/assets/{id}

An upload or a generated output of the workspace, with fresh signed URLs. 404 when the id is unknown, the upload was never completed, or the asset belongs to another workspace.

curl
curl "$LOUPE_BASE_URL/api/v1/assets/ast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c" \
  -H "Authorization: Bearer $LOUPE_API_KEY"

The asset object

FieldTypeDescription
idstringast_… — use it in asset fields of input.
object"asset"
typestringimage, video, audio or model (a 3D model: a GLB file, model/gltf-binary).
sourcestringupload or generated.
mime_typestringThe detected type.
filenamestring or nullThe uploaded file’s name.
bytesinteger or null
width, heightinteger or nullNull for audio and 3D models.
duration_msinteger or nullNull for images and 3D models.
urlstringSigned, valid 6 hours.
thumbnail_urlstring or nullA small WebP preview (images; 3D models when one exists).
download_urlstringSigned, valid 6 hours; downloads as an attachment.
generation_idstring or nullThe generation that produced it (null for uploads).
created_atstring
deleted_atstring or nullSet while it is in the trash: it can no longer be used as an input, and it is deleted for good 30 days later.

Credit balance

Get the balance

GET/api/v1/credits

Answers { available, held }: the workspace's spendable credits and the credits held by generations that are still running.

curl
curl "$LOUPE_BASE_URL/api/v1/credits" \
  -H "Authorization: Bearer $LOUPE_API_KEY"
200 response
{
  "available": 1485,
  "held": 15
}

MCP (AI assistants)

Connect an assistant

POST/api/v1/mcp

Loupe is also a Model Context Protocol server (Streamable HTTP, stateless, JSON responses), so Claude, ChatGPT, Cursor and other MCP clients can generate with it. Authenticate with an API key in the Authorization header, as for the REST API (the same rate limit applies). Generations cost the same credits as with the REST API.

Claude Code
claude mcp add --transport http loupe "$LOUPE_BASE_URL/api/v1/mcp" \
  --header "Authorization: Bearer $LOUPE_API_KEY"
curl
curl -X POST "$LOUPE_BASE_URL/api/v1/mcp" \
  -H "Authorization: Bearer $LOUPE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list"
  }'

MCP tools

ToolArgumentsWhat it does
list_modelstool (optional)Without tool, a compact list of the models available now: id, name, tool, mode, output_type, base_credits and is_default. With tool, that tool's full model objects, input fields included.
generatemodel, input, wait_seconds (0–50, default 45), idempotency_key (optional)Starts a generation and waits for its result.
get_generationid, wait_seconds (0–50, default 0)A generation, after waiting up to wait_seconds for it to finish.
get_credits—The available and held credits, as GET /api/v1/credits.
  • A result carries its data twice: as compact JSON in its text block, after a short summary, and as structuredContent. An error has only the text, except a generation that failed or was canceled, which keeps its data. Output URLs are absolute and signed (valid 6 hours).
  • Media fields of input take an asset id (ast_…, such as the outputs[].id of an earlier generation) or a public https:// URL. Inputs whose size or duration sets the price or the limits accept only asset ids (see field definitions): the upscalers, image-to-video frames, video edit, extend, upscale, relight and character swap, lip sync, talking video, motion transfer, reimagine, camera angle, expand, variations, vectorize, mockups, split into layers, the video tools other than joining clips and still to clip, and others. To use a file of your own there, upload it with POST /api/v1/uploads and the same API key, then pass its asset_id.
  • idempotency_key (1–128 visible ASCII characters) works like the REST Idempotency-Key header and shares its keys: a retry with the key of an earlier call returns that generation instead of starting (and charging) another one; the same key with another model is a conflict error.
curl
curl -X POST "$LOUPE_BASE_URL/api/v1/mcp" \
  -H "Authorization: Bearer $LOUPE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "generate",
      "arguments": {
        "model": "nano-banana-2.1",
        "input": {
          "prompt": "a lighthouse on a cliff at dawn, soft fog"
        },
        "idempotency_key": "lighthouse-0002"
      }
    }
  }'

Waiting for a result

generate and get_generation wait up to wait_seconds for the generation to finish, but one request waits at most 45 seconds in all, counted from when it reaches the server (starting the generation included). A generation that is still running then is returned with its id and status (its outputs are saved in the background): call get_generation with that id to check again. At most 4 calls per API key wait at the same time (per server instance); while 4 are waiting, another call answers at once with the current status, as with wait_seconds 0.

MCP errors and transport

  • A tool that fails returns a result with isError: true and a text such as insufficient_credits: … (the REST API's error codes). Invalid arguments are reported the same way, naming each bad field (path: message; …), and so is a generation that ended failed or canceled.
  • JSON-RPC errors: -32602 for an unknown or missing tool name, or params or arguments that are not an object; -32601 for an unknown method; -32600 for an invalid message; -32603 for an unexpected server error. An error carries the request's id whenever it is a string or a number (null otherwise).
  • A request is one JSON-RPC message or a batch of up to 10: an array, answered with the array of its replies. Notifications and responses get no reply, so a body of only those answers 202 with no body. A message that cannot be accepted (an invalid notification, an id that is neither a string nor a number) gets a -32600 error with id null, with status 400 unless the same batch holds a request; a batch that is empty or holds more than 10 messages gets 400 too.
  • initialize negotiates protocol 2025-11-25, 2025-06-18 or 2025-03-26: the version the client asks for when it is one of them, else the newest. An MCP-Protocol-Version header with any other value gets 400 with a JSON-RPC error (-32600); a request without the header is accepted.
  • Requests from web pages of other origins get 403 forbidden; GET (no server stream) gets 405.

Prompt tools

Two helpers for writing prompts. They are free — no credits are used — and limited to 20 requests per minute per API key and 300 requests per rolling 24 hours per workspace (the Loupe app's prompt tools count against the same daily allowance). Over a limit they answer 429 rate_limited with Retry-After. Both answer 200 with { "prompt": "…" }: at most 1500 characters, ready to use as a generation's input.prompt.

Enhance a prompt

POST/api/v1/prompts/enhance

A richer version of a prompt for the image or the video generator. It keeps the subject, intent and details you gave and fills in what is missing: setting, composition, lighting and style, and for video the action and the camera movement. An empty prompt returns a new idea.

Body fieldTypeDescription
promptstringThe prompt to improve (at most 4000 characters; may be empty).
kindstringimage or video: the generator the prompt is for.
languagestring or nullOptional language to write in, as a BCP 47 tag such as en or pt-BR. Default: the prompt's own language (English for a new idea).
curl
curl -X POST "$LOUPE_BASE_URL/api/v1/prompts/enhance" \
  -H "Authorization: Bearer $LOUPE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "a lighthouse on a cliff at dawn",
    "kind": "image"
  }'
200 response
{
  "prompt": "A lone white lighthouse on a rugged sea cliff at dawn, its lamp still glowing as the first pink light breaks over a calm, misty sea. Waves curl against dark rocks below and gulls circle the tower. Wide composition with a low horizon, soft pastel colours, cinematic photograph with a 35 mm lens and gentle film grain."
}

Describe an image

POST/api/v1/prompts/describe

An English prompt that would recreate an image of the workspace: an upload or a generated image that is not in the trash.

Body fieldTypeDescription
asset_idstringThe image's ast_… id.
curl
curl -X POST "$LOUPE_BASE_URL/api/v1/prompts/describe" \
  -H "Authorization: Bearer $LOUPE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "asset_id": "ast_7c41e0d9a2b34f6e8d1c5b9a0f2e3d4c"
  }'
200 response
{
  "prompt": "A candid portrait of a young woman with short curly hair and a mustard-yellow knit sweater, smiling over her shoulder on a sunlit city street. Warm late-afternoon light, shallow depth of field with softly blurred storefronts behind her, natural colours, shot on a 50 mm lens."
}

Prompt tool errors

  • 422 validation_error — an invalid body. An asset_id that is unknown, belongs to another workspace, was never completed, is in the trash or is not an image has an issue on asset_id.
  • 400 content_policy — the prompt, the image or the result was refused by the content policy.
  • 429 rate_limited — over a limit above; wait Retry-After seconds.
  • 502 provider_error — the prompt assistant failed or took too long to answer. Nothing is retried for you; try again.
  • 503 model_unavailable — the prompt tools are not available on this deployment right now.

Webhooks

Pass webhook_url when you create a generation and Loupe calls it once the generation reaches a final status. The URL must be a public https:// URL on the default port, without credentials, not a local or private address, and at most 2048 characters once percent-encoded (422 otherwise).

Events

typeSent when
generation.succeededThe outputs are ready.
generation.failedIt failed (see data.error).
generation.canceledIt was canceled.

The request is a POST with a JSON body: id (the event id, whd_…, equal to the webhook-id header), type, created_at (when the event happened) and data (the generation at the time of sending, with fresh output URLs):

event
{
  "id": "whd_9e8d7c6b5a4f4e3d2c1b0a9f8e7d6c5b",
  "type": "generation.succeeded",
  "created_at": "2026-11-07T10:15:24.870Z",
  "data": {
    "id": "job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f",
    "object": "generation",
    "model": "nano-banana-2.1",
    "tool": "image",
    "status": "succeeded",
    "input": {
      "prompt": "a lighthouse on a cliff at dawn, soft fog",
      "aspect_ratio": "16:9",
      "resolution": "1K",
      "num_images": 1
    },
    "credits_cost": 15,
    "error": null,
    "outputs": [
      {
        "id": "ast_3a9d6f1c2b7e4d5a8c0b1e2f3a4b5c6d",
        "type": "image",
        "mime_type": "image/png",
        "url": "https://loupe.example.com/api/files/ws/ws_4c1d8e2f9a3b4c5d6e7f8091a2b3c4d5/gen/job_0f8c2e3d6b4a4b0e9c1d2a3b4c5d6e7f/0.png?exp=1794067324&sig=5d0c…",
        "width": 1344,
        "height": 768,
        "duration_ms": null
      }
    ],
    "created_at": "2026-11-07T10:15:02.114Z",
    "completed_at": "2026-11-07T10:15:24.870Z"
  }
}

Signatures

Webhooks follow the Standard Webhooks specification, so its libraries can verify them too. Each request carries:

request
POST /hooks/loupe HTTP/1.1
content-type: application/json
user-agent: Loupe-Webhooks/1
webhook-id: whd_9e8d7c6b5a4f4e3d2c1b0a9f8e7d6c5b
webhook-timestamp: 1794046525
webhook-signature: v1,qRF1OaNb8pj5pyjSo9EKWmgSOF1J/DlGpcVMGLF4264=
  • webhook-id — the event id; it stays the same when a delivery is retried.
  • webhook-timestamp — when this attempt was sent, in Unix seconds.
  • webhook-signature — v1, followed by the base64 HMAC-SHA256 of {webhook-id}.{webhook-timestamp}.{raw body}, keyed with your signing secret decoded from base64 (the part after whsec_). The header may list several space-separated signatures; accept the request if any v1 one matches.

Your signing secret is per workspace: owners and admins reveal or rotate it in Settings → API keys. After a rotation, every request (retries included) is signed with the new secret.

To verify: compute the signature over the raw body exactly as received (before parsing it), compare it in constant time, and reject timestamps more than 5 minutes from your clock. To test your verifier: the example request above was signed with the example secret whsec_bG91cGUtZG9jcy1leGFtcGxlLXNlY3JldC0wMDAwMDE= over the compact JSON (JSON.stringify) of the event shown, and the Standard Webhooks test vector must verify too — secret whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw, id msg_p5jXN8AQM9LWM0D4loKWxJek, timestamp 1614265330, body {"test": 2432232314}, signature v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=.

Verifying in Node

verify-webhook.mjs
// verify-webhook.mjs — Node 18+, no dependencies
import { createHmac, timingSafeEqual } from 'node:crypto';

const TOLERANCE_SECONDS = 5 * 60;

function readHeader(headers, name) {
  const value = typeof headers.get === 'function' ? headers.get(name) : headers[name];
  return Array.isArray(value) ? value.join(' ') : (value ?? '');
}

/**
 * Verifies a Loupe webhook and returns the parsed event; throws when it is not authentic.
 * secret:  your workspace's signing secret ("whsec_…")
 * headers: Node's req.headers, or a Fetch Headers object
 * rawBody: the exact request body as received (string or Buffer), before any JSON parsing
 */
export function verifyWebhook(secret, headers, rawBody, nowSeconds = Math.floor(Date.now() / 1000)) {
  const id = readHeader(headers, 'webhook-id');
  const timestamp = readHeader(headers, 'webhook-timestamp');
  const signatures = readHeader(headers, 'webhook-signature');
  if (!id || !/^\d+$/.test(timestamp) || !signatures) throw new Error('Missing webhook headers');
  if (Math.abs(nowSeconds - Number(timestamp)) > TOLERANCE_SECONDS) throw new Error('Webhook timestamp out of range');

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = createHmac('sha256', key).update(`${id}.${timestamp}.`).update(rawBody).digest();
  const valid = signatures.split(' ').some((entry) => {
    const [version, signature] = entry.split(',');
    if (version !== 'v1' || !signature) return false;
    const given = Buffer.from(signature, 'base64');
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
  if (!valid) throw new Error('Invalid webhook signature');
  return JSON.parse(rawBody.toString());
}

Using it with Node's built-in HTTP server:

server.mjs
// server.mjs — receive Loupe webhooks with Node's built-in HTTP server
import { createServer } from 'node:http';
import { verifyWebhook } from './verify-webhook.mjs';

const secret = process.env.LOUPE_WEBHOOK_SECRET; // Settings → API keys → Webhook signing secret
const seen = new Set(); // use your database in production
const MAX_BODY_BYTES = 1024 * 1024; // Loupe events are a few KB; refuse anything larger before buffering it

createServer((req, res) => {
  const chunks = [];
  let size = 0;
  req.on('data', (chunk) => {
    size += chunk.length;
    if (size > MAX_BODY_BYTES) {
      res.writeHead(413, { connection: 'close' }).end();
      req.destroy();
      return;
    }
    chunks.push(chunk);
  });
  req.on('end', () => {
    let event;
    try {
      event = verifyWebhook(secret, req.headers, Buffer.concat(chunks));
    } catch {
      res.writeHead(400).end();
      return;
    }
    res.writeHead(204).end(); // answer quickly; do slow work afterwards
    if (seen.has(event.id)) return; // the same event can arrive more than once
    seen.add(event.id);
    if (event.type === 'generation.succeeded') {
      for (const output of event.data.outputs) console.log('ready:', output.url);
    }
  });
}).listen(3000);

Delivery and retries

  • Answer with any 2xx status within 10 seconds; do slow work after responding. Redirects are not followed.
  • Any other status, a timeout or a network error is retried after 30 s, 2 min, 10 min, 30 min, 1 h, 3 h, 6 h and 12 h (9 attempts in total); after that the event is dropped. Answer 410 Gone to stop the retries of an event at once.
  • The URL is checked again before every attempt; if it is no longer allowed, the event is dropped.
  • An event can arrive more than once, and events of different generations in any order: deduplicate on webhook-id and treat GET /api/v1/generations/{id} as the source of truth.

Need a key? Create one in Settings → API keys. Questions: support@loupe.local.