Quick start
Set up your API key
Les abonnements Pro, Pro Max, Enterprise et Enterprise Plus et les packs Creator, Business, Enterprise et Enterprise Plus incluent l’API. Un pack admissible conserve l’historique et les téléchargements à solde nul ; générer exige des crédits. Un remboursement intégral ou une suspension pour litige retire uniquement l’admissibilité de cet achat.
Envoyez Authorization: Bearer YOUR_API_KEY depuis votre serveur. Les cookies du site ne sont pas des identifiants API. Chaque requête vérifie l’admissibilité et les permissions.
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.
Gestion API Les clésCheck 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.
Seule la présentation de génération consomme des crédits de compte. Les citations et les créations clés ne consomment pas des crédits. Les échecs du fournisseur utilisent le processus existant de remboursement et de réconciliation. Ne soumettez pas une nouvelle clé d'identité alors que le résultat initial est inconnu.
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
Chaque clé permet 60 Les demandes authentifiées par minute. a 429 La réponse inclut Retry-After. les clés expirent dans 1–365 des jours et peut être révoqué immédiatement.
401 : clé invalide. 402 : crédits insuffisants. 403 : admissibilité ou permission API manquante. 409 : devis modifié ou conflit. 422 : entrée non prise en charge. 429 : limite. 503 : indisponible. Vérifiez un résultat payant incertain avec l’identifiant d’origine.
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.