Skip to content
Guides

OpenAPI Client Generator for an Image and Video API

Point an OpenAPI client generator at one spec and get a typed client for image and video generation in TypeScript, Python or Java, kept in sync.

Updated 5 min read

An OpenAPI client generator reads an API's spec and writes the client for you: typed request bodies, typed answers and one function per endpoint. Frameport publishes its whole API as one OpenAPI 3.1 document at /openapi.json, so a couple of commands give you a typed client for image and video generation in TypeScript, Python or Java, and a misspelled field fails in your editor instead of in production.

This guide uses three generators we ran against that spec: openapi-typescript with openapi-fetch, openapi-python-client, and OpenAPI Generator. Each sample prices a Seedance 2.5 clip, submits it under a cost cap and reads it until it settles. The last part shows what to keep out of generated code: model ids and their options.

Where the spec lives

The document is served at https://frameport.ai/openapi.json, built from the same source as the API reference and updated with each release. It needs no key to download:

curl -O https://frameport.ai/openapi.json

It describes every endpoint under /v1, grouped by tag (Images, Videos, Clip edits, Uploads, Generations, Files, Models, Account), with an operationId for each, such as createVideoGeneration or quoteGeneration. It also declares the Bearer key scheme, the Idempotency-Key header and the error body every failure shares. The OpenAPI page lists other uses: import it into Postman, Insomnia or Bruno, or hand it to a coding agent along with llms.txt.

What the spec leaves out is deliberate:

In the specRead at run time from GET /v1/models
Paths, methods and operation idsWhich model ids exist
Request bodies, answers and error bodiesEach model's prices
The key scheme and Idempotency-KeyResolutions, durations and aspect ratios per model
Statuses, types and other fixed enumsClip limits of each editor

model is a plain string in every request schema, and options is an open object, because the catalog changes far more often than the endpoints. A client generated today keeps compiling when a model is added tomorrow.

TypeScript client: openapi-typescript and openapi-fetch

openapi-typescript turns the spec into a declaration file with no runtime code at all, and openapi-fetch is a thin typed wrapper over fetch that reads those declarations. Together they check every path, parameter and body at compile time:

npm install openapi-fetch
npm install --save-dev openapi-typescript typescript@5
npx openapi-typescript https://frameport.ai/openapi.json -o frameport.d.ts

openapi-typescript 7 runs on TypeScript 5. In our test it stopped with an error when only a newer TypeScript was installed, so pin version 5 next to it, as above. Then, in a project whose package.json has "type": "module":

clip.ts
import createClient from 'openapi-fetch'
import type { components, paths } from './frameport.js' // the frameport.d.ts generated above

type Generation = components['schemas']['Generation']

const api = createClient<paths>({
  baseUrl: 'https://frameport.ai',
  headers: { Authorization: `Bearer ${process.env.FRAMEPORT_API_KEY}` },
})

const body = {
  model: 'seedance-2-5',
  prompt: 'A lighthouse keeper climbs the spiral stairs at dusk, lantern swinging, wind howling outside',
  duration: 5,
  resolution: '720p',
  aspect_ratio: '9:16',
} as const

// Free: the price, and whether the balance covers it
const quote = await api.POST('/v1/generations/quote', { body })
if (quote.error) throw new Error(quote.error.error.message)
console.log('price', quote.data.price_usd, 'covered', quote.data.enough_balance)

const submitted = await api.POST('/v1/videos/generations', {
  params: { header: { 'Idempotency-Key': 'lighthouse-stairs-1' } },
  body: { ...body, max_cost_usd: quote.data.reserved_usd },
})
if (submitted.error) throw new Error(`${submitted.error.error.code}: ${submitted.error.error.message}`)

let gen: Generation = submitted.data
while (gen.status === 'queued' || gen.status === 'running') {
  await new Promise(resolve => setTimeout(resolve, 5000))
  const read = await api.GET('/v1/generations/{id}', { params: { path: { id: gen.id } } })
  if (read.error) throw new Error(read.error.error.message)
  gen = read.data
}
if (gen.error) throw new Error(`failed, nothing charged: ${gen.error.message}`)
console.log(gen.outputs[0]?.url, 'charged', gen.cost_usd)

Recent Node versions run a .ts file like this one directly; on an older one, use npx tsx clip.ts. Every answer comes back as { data, error }: error is typed as the shared error body, so error.error.code autocompletes, and data is the Generation schema. A wrong path, a missing prompt or an aspect_ratio the API never takes is a compile error.

Python client: openapi-python-client

openapi-python-client writes a whole installable package, with a function per operation and a class per schema:

uvx openapi-python-client generate --url https://frameport.ai/openapi.json
pip install ./frameport-api-client

The project is named after the spec's title, here frameport-api-client, with the package frameport_api_client. Three details save time. It skips POST /v1/uploads with a warning, because that endpoint takes the raw file rather than JSON: send uploads with requests or httpx, as the guide to sending your own files shows. Enum values that are not valid Python names get generated names (the aspect ratio "16:9" becomes a member like VALUE_0), so build bodies with from_dict and plain strings. And the package declares its own Python floor in pyproject.toml, 3.11 with the release we used.

clip.py
import os
import time

from frameport_api_client import AuthenticatedClient
from frameport_api_client.api.generations import get_generation, quote_generation
from frameport_api_client.api.videos import create_video_generation
from frameport_api_client.models import CreateVideoGenerationBody, Error, QuoteGenerationBody

client = AuthenticatedClient(base_url="https://frameport.ai", token=os.environ["FRAMEPORT_API_KEY"])
clip = {"model": "seedance-2-5", "duration": 5, "resolution": "720p", "aspect_ratio": "9:16"}

quote = quote_generation.sync(client=client, body=QuoteGenerationBody.from_dict(clip))
if isinstance(quote, Error):
    raise SystemExit(quote.error.message)
print("price:", quote.price_usd, "covered:", quote.enough_balance)

gen = create_video_generation.sync(
    client=client,
    idempotency_key="lighthouse-stairs-1",
    body=CreateVideoGenerationBody.from_dict({
        **clip,
        "prompt": "A lighthouse keeper climbs the spiral stairs at dusk, lantern swinging, wind howling outside",
        "max_cost_usd": quote.reserved_usd,
    }),
)
if isinstance(gen, Error):
    raise SystemExit(f"{gen.error.code}: {gen.error.message}")

while gen.status in ("queued", "running"):
    time.sleep(5)
    gen = get_generation.sync(gen.id, client=client)
if gen.error:
    raise SystemExit(f"Failed, nothing charged: {gen.error.message}")
print(gen.outputs[0].url, "charged", gen.cost_usd)

A documented error status comes back as the Error model rather than an exception, hence the isinstance checks. Each function also has an asyncio twin for async code. For the same flow with plain requests and no generated code, see the AI video generation API in Python.

OpenAPI Generator for Java, Spring Boot and more

OpenAPI Generator is the long-standing open-source tool, maintained on GitHub by the OpenAPITools project, that writes clients for many languages from one spec. Its npm wrapper downloads the generator and needs Java on the machine:

npx @openapitools/openapi-generator-cli generate -i https://frameport.ai/openapi.json -g python -o frameport-py
npx @openapitools/openapi-generator-cli generate -i https://frameport.ai/openapi.json -g typescript-fetch -o frameport-ts
npx @openapitools/openapi-generator-cli generate -i https://frameport.ai/openapi.json -g java --library restclient -o frameport-java

What we saw with each:

TargetWhat you getNote
pythonOne API class per tag (VideosApi, GenerationsApi…), with methods like create_video_generationTakes the body as a model and idempotency_key as a keyword
typescript-fetchClasses per tag over fetch, with runtime modelsThe Error schema is renamed ModelError
javaVideosApi.createVideoGeneration(request, idempotencyKey)--library restclient, webclient or resttemplate builds on Spring's HTTP clients

Each run warns that OpenAPI 3.1 support is still in beta; with this spec, all three finished without errors. The spring generator is a different thing: it writes server stubs for an API you host, not a client for one you call.

Keeping model options current

Generated code covers the endpoints. The catalog lives at run time: GET /v1/models lists every model with its prices and options, and GET /v1/models/{id} returns one, both without a key (models). Since options is an open object in the spec, name the fields your code relies on and check a request against the live values, for instance to build a form or to fail early in a batch:

options.ts
import createClient from 'openapi-fetch'
import type { paths } from './frameport.js'

// options is an open object in the spec: declare the fields you read
interface VideoOptions {
  resolutions: string[]
  durations: { min: number, max: number, step: number }
  aspect_ratios: string[]
}

const api = createClient<paths>({ baseUrl: 'https://frameport.ai' })

export async function checkClip(model: string, duration: number, resolution: string, aspectRatio: string) {
  const { data, error } = await api.GET('/v1/models/{id}', { params: { path: { id: model } } })
  if (error) throw new Error(error.error.message)
  const options = data.options as unknown as VideoOptions
  const { min, max, step } = options.durations
  const problems: string[] = []
  if (!options.resolutions.includes(resolution)) problems.push(`resolution: one of ${options.resolutions.join(', ')}`)
  if (duration < min || duration > max || (duration - min) % step !== 0) problems.push(`duration: ${min} to ${max} s, in steps of ${step}`)
  if (!options.aspect_ratios.includes(aspectRatio)) problems.push(`aspect_ratio: one of ${options.aspect_ratios.join(', ')}`)
  return problems
}

console.log(await checkClip('seedance-2-5', 5, '720p', '9:16')) // [] when the clip fits

The server applies the same rules anyway: a value a model does not take is refused with 400 invalid_request before anything is held, and the message lists what the model takes.

The endpoints change rarely, and the changelog announces new fields. To catch a change without reading it, regenerate in CI and fail when the output moves:

CI: fail when the spec changed
npx openapi-typescript https://frameport.ai/openapi.json -o src/frameport.d.ts
git diff --exit-code src/frameport.d.ts

For two small apps built on the same endpoints, see the Discord bot and Telegram bot guides.

FAQ

What is OpenAPI Generator?

An open-source project, maintained on GitHub by OpenAPITools, that turns an OpenAPI document into client libraries, server stubs and documentation for many languages. You run it from its CLI, its npm wrapper (which needs Java) or Docker, with -g naming the target.

Which OpenAPI client generator is best for TypeScript?

For a small footprint, openapi-typescript with openapi-fetch: types only, a thin wrapper over fetch, and nothing to regenerate at run time. OpenAPI Generator's typescript-fetch target writes classes and runtime models instead, which some teams prefer.

Can I generate a Spring Boot client from an OpenAPI spec?

Yes: -g java with --library restclient, webclient or resttemplate writes a client on Spring's own HTTP clients. The spring generator writes server stubs, the other direction.

Does FastAPI generate an OpenAPI client?

FastAPI writes an OpenAPI spec from your own Python code, and OpenAPI Generator's python-fastapi target writes a FastAPI server. To call this API from a FastAPI app, generate a Python client with openapi-python-client or -g python and use it inside your endpoints, with the key on your server.

Why are model ids plain strings in the generated client?

Models, prices and options change more often than the endpoints, so the spec leaves them open and GET /v1/models lists them at run time. Your client keeps compiling when the catalog grows, and a model id the API does not know is refused with model_not_found.

Guides6 min read

AI Video API Error Codes: What to Retry

AI video API error codes explained: what each status and code means, which to retry, which cost nothing, and a retry loop that never pays twice.

Start building.

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