Quick start
Set up your API key
Assinaturas Pro, Pro Max, Enterprise e Enterprise Plus e pacotes Creator, Business, Enterprise e Enterprise Plus incluem API. Um pacote válido mantém histórico e downloads com saldo zero; gerar exige créditos. Reembolso total ou suspensão por disputa remove apenas a elegibilidade dessa compra.
Envie Authorization: Bearer YOUR_API_KEY pelo servidor. Cookies do site não são credenciais API. Cada solicitação verifica elegibilidade e permissões.
Use Node.js 22 or later. Set GAPTI_ORIGIN to the Gapti site origin and set GAPTI_API_KEY on your server. Give the key models:read, generations:write, and generations:read. Add assets:write if you upload a reference.
Gestão API chavesCheck the model catalog
Call GET /api/v1/models with your API key to see the models and options available to your account.
curl --fail-with-body -H "Authorization: Bearer $GAPTI_API_KEY" "$GAPTI_ORIGIN/api/v1/models"Upload a reference
For the optional upload in this example, set REFERENCE_PNG to a local PNG path. Declare the MIME type and byte count, PUT the file to the returned upload URL, then complete the upload. Use the returned Gapti asset ID from your account in the generation draft.
Gapti accepts single-frame JPEG, PNG, or WebP uploads up to 10 MiB, 40 megapixels, and 16,384 pixels per side. Use referenceAssetIds for an image edit, or firstFrameAssetId for a video model that supports a first frame.
POST /api/v1/uploadsPUT {uploadUrl}POST /api/v1/uploads/{uploadId}/complete
Review the quote
Run the quote command to save normalizedDraft, the full quote, and an idempotency key. Review the total before running submit. Use the quote as returned, including any signature.
For USD quotes, POST /api/v1/quotes/validate accepts the normalized draft and the original quote. If the quote has changed or expired, request and review a new one.
Submit the job
Run submit with the same job file after approving the quote. If the submission outcome is unknown, run submit again with that file to reuse the original body and Idempotency-Key. If the API reports QUOTE_CHANGED, request and review a fresh quote before submitting.
Apenas a submissão de geração consome créditos de conta. Cotas e criação chave não consomem créditos. Fracções do fornecedor usam o processo de reembolso e reconciliação existente. Não submete uma nova chave de identidade enquanto o resultado original é desconhecido.
Poll and download
Run download with the same job file. Poll the returned task kind and ID using pollAfterMs until the job ends. Send the Bearer token to each protected output URL, then follow its download redirect without the token.
Node.js example
Save the example as gapti.mjs. Run each command in order and choose a new job file name for each new job.
node gapti.mjs quotenode gapti.mjs submitnode gapti.mjs download
import { randomUUID } from 'node:crypto'
import { readFile, writeFile } from 'node:fs/promises'
import { basename } from 'node:path'
import { setTimeout as delay } from 'node:timers/promises'
const [command, jobFile = 'gapti-job.json'] = process.argv.slice(2)
const { GAPTI_ORIGIN, GAPTI_API_KEY, REFERENCE_PNG } = process.env
if (!GAPTI_ORIGIN || !GAPTI_API_KEY) {
throw new Error('Set GAPTI_ORIGIN and GAPTI_API_KEY')
}
const origin = new URL(GAPTI_ORIGIN).origin
async function request(path, options = {}) {
const url = new URL(path, origin)
if (url.origin !== origin) throw new Error('Expected a same-origin API URL')
const response = await fetch(url, {
...options,
redirect: 'manual',
headers: { Authorization: 'Bearer ' + GAPTI_API_KEY, ...options.headers },
})
if (!response.ok && response.status !== 302) {
const retry = response.headers.get('Retry-After')
throw new Error(response.status + ' ' + await response.text() +
(retry ? ' (Retry-After: ' + retry + ')' : ''))
}
return response
}
async function post(path, payload, headers = {}) {
return (await request(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify(payload),
})).json()
}
async function uploadPng(file) {
const bytes = await readFile(file)
const mime = 'image/png'
const upload = await post('/api/v1/uploads', {
mime, bytes: bytes.length, fileName: basename(file),
})
await request(upload.uploadUrl, {
method: 'PUT', headers: { 'Content-Type': mime }, body: bytes,
})
const asset = await post('/api/v1/uploads/' +
encodeURIComponent(upload.uploadId) + '/complete')
return asset.id
}
if (command === 'quote') {
const draft = {
"kind": "image",
"modelPreset": "gpt-image-2",
"mode": "text-to-image",
"prompt": "Photograph a yellow ceramic mug on a pale blue background. Light it from the left.",
"aspectRatio": "1:1",
"resolution": "1k",
"outputCount": 1,
"toolId": null,
"negativePrompt": "",
"referenceAssetIds": [],
"generationQuality": null,
"seed": null,
"imageSetMode": false
}
const { items } = await (await request('/api/v1/models')).json()
if (!items.some(item => item.kind === 'image' && item.id === draft.modelPreset)) {
throw new Error('This model is absent from your API catalog')
}
if (REFERENCE_PNG) {
const assetId = await uploadPng(REFERENCE_PNG)
draft.mode = 'image-to-image'
draft.referenceAssetIds = [assetId]
}
const quoted = await post('/api/v1/quotes', { draft })
const submission = {
draft: quoted.normalizedDraft,
quoteAcknowledgement: quoted.quote,
}
await writeFile(jobFile, JSON.stringify({
idempotencyKey: randomUUID(), submission,
}, null, 2), { flag: 'wx', mode: 0o600 })
console.log('Review this quote before submitting:', quoted.quote)
} else if (command === 'submit') {
const job = JSON.parse(await readFile(jobFile, 'utf8'))
const accepted = await post('/api/v1/generations', job.submission, {
'Idempotency-Key': job.idempotencyKey,
})
await writeFile(jobFile + '.accepted', JSON.stringify(accepted), { mode: 0o600 })
console.log(accepted.task)
} else if (command === 'download') {
const accepted = JSON.parse(await readFile(jobFile + '.accepted', 'utf8'))
const { kind, id } = accepted.task
const taskPath = '/api/v1/generations/' + kind + '/' + encodeURIComponent(id)
let wait = accepted.pollAfterMs
let detail
do {
await delay(wait)
detail = await (await request(taskPath)).json()
console.log(detail.status)
wait = detail.pollAfterMs
} while (wait !== null)
if (detail.status === 'failed') throw new Error(JSON.stringify(detail.error))
for (const output of detail.outputs) {
if (!output.downloadUrl) continue
const redirect = await request(output.downloadUrl)
const location = redirect.headers.get('Location')
if (redirect.status !== 302 || !location) throw new Error('Expected a download redirect')
const file = await fetch(new URL(location, origin))
if (!file.ok) throw new Error('Download failed: ' + file.status)
const extension = { 'image/png': 'png', 'image/jpeg': 'jpg',
'image/webp': 'webp', 'video/mp4': 'mp4' }[output.mime] ?? 'bin'
await writeFile(id + '-' + output.index + '.' + extension,
Buffer.from(await file.arrayBuffer()))
}
} else {
throw new Error('Use quote, submit, or download')
}Errors and limits
Cada chave permite 60 Requisitos autenticados por minuto. a 429 A resposta inclui Retry-After. as chaves expiram dentro 1–365 dias e pode ser revogada imediatamente.
401: chave inválida. 402: créditos insuficientes. 403: sem elegibilidade ou permissão API. 409: preço alterado ou conflito. 422: entrada não aceita. 429: limite. 503: indisponível. Confira resultados pagos incertos com a identidade original.
Batch submission
For accounts with expanded USD generation, POST /api/v1/generations/batch accepts 1–10 items. Use a distinct UUID for each clientRequestId and include each item’s normalized draft and quoteAcknowledgement. Each item returns its own accepted task or error. Reuse the original clientRequestId and payload if its submission outcome is unknown.