Skip to content
Concepts

API Key Security for AI Image and Video APIs

API key security for image and video APIs: keep keys on the server, give each app or agent its own, cap every request, watch spend per key, revoke fast.

Updated 7 min read

API key security matters more on an image or video API than almost anywhere else, because every request a key signs starts paid work: whoever holds your key can render clips on your money until you revoke it. The defences are simple and they stack: keep the key on your server, give each app or agent a key of its own, cap what a request may cost, watch spend key by key, and revoke the moment something looks wrong.

This guide shows how each of those works on Frameport, what a key can and cannot reach, and a small server that lets a web page start Seedance 2.5 clips without the key ever leaving it.

Why a leaked key costs money

A leaked key for a read-only API exposes data. A leaked generation key is closer to a card someone else can use: a script submits jobs around the clock, and every clip that comes back is charged to you. OWASP names both halves of the problem in its API Security Top 10: broken authentication (API2:2023), and unrestricted resource consumption (API4:2023), which it warns can drive up operating costs.

Here, a key belongs to one workspace and acts only inside it:

A key canA key cannot
Start images, videos and clip edits on any modelAdd funds or touch the saved card
Read the workspace's generations and download their filesInvite or remove members, or change roles
Upload pictures and clips for its own jobsCreate, list or revoke keys
Price requests and read the balanceChange settings, the content filter included

So the worst a stolen key can do is spend the workspace's balance and read what the workspace has made. Because the balance is prepaid, that loss has a ceiling you set: what sits in the workspace, plus any auto top-up refills you allowed for the month.

Keep keys on the server

A key belongs in your server's environment, as FRAMEPORT_API_KEY or in your host's secret store, and nowhere a user can open it: not in a web page's JavaScript, not inside a mobile app, not in a public repository, a shared notebook or a screenshot. Whatever ships to a device can be read off that device, however it is bundled or obfuscated (keep keys on the server).

Your server then becomes the only caller, and it decides what a user may ask for. The page sends a prompt; the server fixes the model, the length, the resolution and the price cap, so nobody can switch your app to a costlier model by editing a request in the browser:

server.mjs
import { createServer } from 'node:http'

const API = 'https://frameport.ai/v1'
const KEY = process.env.FRAMEPORT_API_KEY // read on the server; the page never sees it

// The page chooses the prompt. Everything that sets the price is fixed here.
const CLIP = { model: 'seedance-2-5', duration: 5, resolution: '480p', aspect_ratio: '9:16', max_cost_usd: 0.6 }

async function callApi(path, init = {}) {
  const res = await fetch(`${API}${path}`, {
    ...init,
    headers: { 'Authorization': `Bearer ${KEY}`, 'Content-Type': 'application/json' },
  })
  return { ok: res.ok, body: await res.json() }
}

function send(res, status, body) {
  res.writeHead(status, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify(body))
}

createServer(async (req, res) => {
  // Check your own sign-in here, before anything reaches the key.
  if (req.method === 'POST' && req.url === '/clips') {
    let raw = ''
    for await (const chunk of req) {
      raw += chunk
      if (raw.length > 10_000) return send(res, 413, { error: 'Too large.' })
    }
    let prompt = ''
    try { prompt = String(JSON.parse(raw).prompt ?? '').trim() } catch {}
    if (!prompt || prompt.length > 1500) return send(res, 400, { error: 'Send a prompt of 1 to 1500 characters.' })

    const { ok, body: gen } = await callApi('/videos/generations', { method: 'POST', body: JSON.stringify({ ...CLIP, prompt }) })
    if (!ok) {
      console.error(gen.error) // keep the details in your logs
      return send(res, 503, { error: 'The clip could not be started. Try again later.' })
    }
    // Save gen.id against the signed-in user, then return only what the page needs.
    return send(res, 202, { id: gen.id, status: gen.status })
  }

  // An id is checked before it goes into a URL
  const match = req.method === 'GET' && /^\/clips\/(gen_[0-9A-Za-z]{22})$/.exec(req.url)
  if (match) {
    // Look the id up in your own records first, so no user reads another's clip.
    const { ok, body: gen } = await callApi(`/generations/${match[1]}`)
    if (!ok) return send(res, 404, { error: 'Not found.' })
    if (gen.error) return send(res, 200, { status: gen.status, error: 'This clip failed and cost nothing.' })
    return send(res, 200, { status: gen.status, url: gen.outputs[0]?.url ?? null })
  }

  send(res, 404, { error: 'Not found.' })
}).listen(3000)

The browser never learns the key, the model or the cap, and the API's error details stay in your logs.

One key per app or agent

Create keys under API keys, one for each place a key lives, and name each after that place: web-prod, web-staging, n8n-nightly, claude-code-laptop. A workspace can hold up to 20 active keys. Splitting them pays off three ways:

  • You see who spent what. Each generation records the key that made it, the Library names that key on each output, and Usage splits spend by key over 7, 30 or 90 days, with a CSV export.
  • You notice a key that should be quiet. The key list shows when each key was last used. A staging key busy at 3 a.m. deserves a look.
  • You can revoke one place alone. The other keys keep running while you replace the one in trouble.

Only a hash of each key is stored. The secret appears once, when you create it, and afterwards the dashboard and the API show nothing but its last four characters. To tell which key a script holds, call GET /v1/account: it returns the key's id, name and last four characters, never the secret, and that is what your logs should record too.

Two more guards are built in. Creating a key needs a confirmed email address, and every new key sends its creator an email with the key's name and last four characters: if one arrives that you did not expect, someone has your login, so revoke the key and change your password. And only owners, admins and developers can create or revoke keys, so colleagues who only top up and read the bills can have the billing role, which cannot.

AI agents need the rule more than anyone, since an agent decides on its own when to start a job. Connect each one to the MCP server with a key of its own, kept in its client's config on your own machine and never in a repository you share. The MCP server guide sets this up in Claude Code, Claude Desktop and Cursor.

For a harder wall, use workspaces. A key spends only the balance of the workspace it was made in, so a sandbox workspace with a small balance for tests keeps a leaked test key away from the production budget (keys and workspaces). The guide for agencies and teams applies the same idea with one workspace per client.

Caps and alerts that limit the damage

No key is safe forever, so set limits that still hold the day one leaks:

ControlWhere you set itWhat it stops
max_cost_usdOn each requestA request priced above the cap is refused with 400 max_cost_exceeded before anything is held
The prepaid balanceThe workspaceNothing runs past it: 402 insufficient_balance, and nothing is charged
Auto top-upBillingRefills stop after the number of times a month you allowed, and each one sends a receipt
Rate limitsEvery workspace60 requests that start work a minute and 20 jobs at once, shared by all its keys, the Studio and the MCP server
Low-balance alertBillingAn email when the balance falls under the level you choose
Idempotency-KeyOn each requestA retried request gets the first job back instead of paying twice

The rate limits turn a leak from a sudden drain into something you can catch in time: a runaway script can never hold more than 20 jobs open, and past the limits it gets 429 with a Retry-After header (rate limits). The guide to 429 errors shows how to back off, and idempotency keys make the retry safe.

The per-request cap is the cheapest of these to add. Price the request for free with POST /v1/generations/quote, then send the quoted hold as max_cost_usd, as the server above does with a fixed value (quotes and caps).

Revoking a key

Revoke a key from API keys and it stops at once: the next request signed with it gets this answer.

401 Unauthorized
{
  "error": {
    "code": "unauthorized",
    "message": "Missing, invalid or revoked API key. Send \"Authorization: Bearer <key>\".",
    "request_id": "req_2Wd8XbLq5mT9vRn1Kc7Y"
  }
}

Jobs the key had already started still finish and are charged as usual. A revoked key cannot be restored, so the way back is always a new key.

To rotate a key without downtime, go in this order:

  1. Create the new key, named with the date (web-prod-2026-11).
  2. Deploy it to the app and restart it.
  3. Watch the old key's last-used time stop moving.
  4. Revoke the old key.

Keys have no expiry date here: a key works until someone revokes it.

If a key has leaked, revoke it first and look into it afterwards. Then read its spend in Usage by key, check what it made in the Library, where each output names its key, and replace it everywhere it was used. A key pushed to a public repository stays in the history even after the commit is reverted, so treat it as burnt from the moment of the push.

The Discord bot and Telegram bot guides keep their keys on the server.

FAQ

How do I protect an API key in a web or mobile app?

Keep it out of the app. The page or the app calls your own server, which holds the key in an environment variable, fixes the model and the price cap, and calls the API itself. Anything shipped to a browser or a phone can be read by whoever uses it.

What happens if my API key leaks?

Whoever has it can spend the workspace's balance and read its generations until you revoke it, but cannot add funds, invite anyone or change settings. Revoke it under API keys, where it stops working at once, then check its spend by key and deploy a new one.

Can a leaked API key turn off the content filter?

No. The filter changes only in the dashboard's Settings, by an owner or an admin of the workspace, and no API route touches it. Payments, members and keys are out of a key's reach in the same way.

How often should I rotate API keys?

Keys here never expire on their own, so the schedule is yours: whenever someone who had access leaves, at once after any possible leak, and otherwise as often as your security policy asks. Create the new key, deploy it, watch the old one go quiet, then revoke it.

How do I keep a key safe in Claude Code or Cursor?

Give the agent its own key, named after it, in the client's config on your own machine. Keep that config out of shared repositories, and revoke the key alone if the agent misbehaves. Its spend shows under its own name in Usage.

What are the OWASP best practices for API key security?

The OWASP API Security Top 10 ranks broken authentication and unrestricted resource consumption among the main API risks, and its Secrets Management Cheat Sheet covers storing, auditing, rotating and revoking secrets, and catching them before they are committed. On a paid generation API, that comes down to secrets on the server, one key per use, caps and alerts, and fast revocation.

Start building.

Your API key is free. Top up from $10 when you are ready.