الانتقال إلى المحتوى
All API documentation

Quick start

Set up your API key

تشمل اشتراكات Pro وPro Max وEnterprise وEnterprise Plus وحزم Creator وBusiness وEnterprise وEnterprise Plus الوصول إلى API. تحتفظ الحزمة المؤهلة بالسجل والتنزيل عند نفاد الرصيد؛ ويتطلب الإنشاء الجديد رصيدًا كافيًا. يسحب الاسترداد الكامل أو التعليق بسبب نزاع أهلية تلك العملية فقط.

أرسل 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.

فقط تسليم الجيل يستهلك الائتمانات الحسابية. لا تستهلك الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات الائتمانات.

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. keys expires داخل 1–365 يمكن إلغاءها على الفور ويمكن إلغائها على الفور.

401: مفتاح غير صالح. 402: رصيد غير كافٍ. 403: أهلية API أو إذن مفقود. 409: تغير السعر أو تعارض. 422: إدخال غير مدعوم. 429: حد الطلبات. 503: غير متاح مؤقتًا. تحقق من النتائج المدفوعة غير المؤكدة بهوية الطلب الأصلية.

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.