본문으로 건너뛰기
All API documentation

Quick start

Set up your API key

Pro, Pro Max, Enterprise, Enterprise Plus 구독과 Creator, Business, Enterprise, Enterprise Plus 크레딧 팩은 API를 포함합니다. 해당 팩은 잔액이 0이어도 기록 조회와 다운로드가 가능하며 새 생성에는 크레딧이 필요합니다. 전액 환불 또는 분쟁으로 인한 정지는 해당 구매의 자격만 철회합니다.

서버에서 Authorization: Bearer YOUR_API_KEY를 전송하세요. 웹사이트 쿠키는 API 인증에 사용할 수 없습니다. 매 요청마다 API 자격과 키 권한을 확인합니다.

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.

관리 API 열쇠

Check 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.

  1. POST /api/v1/uploads
  2. PUT {uploadUrl}
  3. 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.

유일한 세대 제출은 계정 크레딧을 소비합니다. 인용문과 키 창조는 크레딧을 소비하지 않습니다. 공급자의 실패는 기존 환불 및 합의 과정을 사용합니다. 원래 결과가 알려지지 않은 동안 새로운 IDPotence 키를 제출하지 마십시오.

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.

  1. node gapti.mjs quote
  2. node gapti.mjs submit
  3. node 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

각 키는 분당 인증된 요청 60회를 허용합니다. 429 응답에는 Retry-After가 포함됩니다. 키는 1–365일 이내에 만료되며 즉시 폐기할 수 있습니다.

401: 잘못된 키. 402: 크레딧 부족. 403: API 자격 또는 권한 없음. 409: 견적 변경 또는 충돌. 422: 지원하지 않는 입력. 429: 요청 한도. 503: 일시적 사용 불가. 유료 처리 결과가 불명확하면 원래 요청 ID로 확인하세요.

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.