gpt api

GPT API Quickstart: Create and Query Your First Media Task

Configure a key, select a model, request a credit quote, submit a generation and query its task using the current media APIs, with cURL, Python and JavaScript examples.

Last updated: 2026-11-12

Before you begin

This guide uses the site’s media-task interface, with text-to-image as the example. Sign in, create a user key in API key management and verify your available balance in credit records. Available models and inputs come from the current catalog.

Submitting a generation consumes account credits. Quote first, review the cost, then run the generation section manually. Placeholders below are not usable keys, models or task IDs. These examples do not activate upstream models or retry submissions automatically.

1. Configure your origin and key, then select a model

Set environment variables on your server or local terminal. Use the site origin without appending /v1, a language prefix or an endpoint path.

export GPT_API_BASE_URL="https://gptapi.app"
export GPT_API_KEY="sk_replace_with_your_key"

curl -i "$GPT_API_BASE_URL/api/ai/router01/models?type=image"

Check that the response code is 0. Choose a model in data that accepts text-to-image requests and copy its slug. Inspect params for required fields and defaults. An image-input-only model cannot serve the text-only example below.

Save this JSON as gptapi-request.json and replace REPLACE_WITH_IMAGE_MODEL_SLUG with the actual slug. Supply any additional required fields in options.params; otherwise leave the object empty.

{
  "mediaType": "image",
  "model": "REPLACE_WITH_IMAGE_MODEL_SLUG",
  "prompt": "A small blue ceramic cup on a plain cream background, soft daylight",
  "options": {
    "params": {}
  }
}

The top-level prompt is the generation prompt. Supply reference HTTP(S) URLs through top-level imageUrls, videoUrls or audioUrls, not duplicated prompt or media fields inside options.params. Use only parameters declared by the selected model.

2. Quote, then submit once

Get a credit estimate using the same request JSON:

curl -i -X POST "$GPT_API_BASE_URL/api/ai/router01/quote" \
  -H "Content-Type: application/json" \
  --data-binary @gptapi-request.json

When the HTTP request succeeds and code is 0, inspect data.credits. Quoting does not create a task; submission recalculates the cost. After confirming the cost and available balance, run:

curl -i -X POST "$GPT_API_BASE_URL/api/ai/generate" \
  -H "Authorization: Bearer $GPT_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @gptapi-request.json

An accepted task has the following shape. IDs and credit values are illustrative, not an actual task or model tariff. The response may include additional fields.

{
  "code": 0,
  "message": "ok",
  "data": {
    "id": "example_task_id",
    "dbId": "example_task_id",
    "taskId": "example_task_id",
    "mediaType": "image",
    "taskStatus": "queued",
    "taskInfo": {},
    "costCredits": 40,
    "remainingBalance": 960
  }
}

Save data.id. A queued acknowledgement is not a finished image. HTTP 200 with code: -1 is still a business failure; address message instead of reading a nonexistent task ID.

3. Query the original task

Replace the placeholder with data.id from the acknowledgement:

export GPT_API_TASK_ID="replace_with_data_id"

curl -i --get "$GPT_API_BASE_URL/api/ai/task" \
  -H "Authorization: Bearer $GPT_API_KEY" \
  --data-urlencode "taskId=$GPT_API_TASK_ID"
  • queued, pending, processing: the task is not finished. Wait before querying the same ID again.
  • success: inspect media results in data.taskInfo, such as images[].imageUrl for images or videos[].videoUrl for videos. Result fields vary by media type.
  • failed, canceled: stop polling and inspect data.taskInfo.userErrorCode and account credit records.

A query returning code: 0 only means the query succeeded. Also check data.taskStatus. Starting with a 5–10 second polling interval is a client recommendation, not a service deadline or quota guarantee. Bound the total wait and retain the ID so you can resume later.

For batches, use comma-separated taskIds=id1,id2, at most 10 per request. Batch results are in data.tasks. The Python and JavaScript examples below submit only once; query afterward as described here. They do not create automatic retry tasks.

Python: submit the same request JSON

Run after setting the environment variables, saving the request JSON and confirming the quote. This example uses only the Python standard library.

import json
import os
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen

base = os.environ["GPT_API_BASE_URL"].rstrip("/")
payload = Path("gptapi-request.json").read_bytes()
request = Request(
    base + "/api/ai/generate",
    data=payload,
    headers={
        "Authorization": "Bearer " + os.environ["GPT_API_KEY"],
        "Content-Type": "application/json",
    },
    method="POST",
)

try:
    with urlopen(request, timeout=60) as response:
        result = json.load(response)
except HTTPError as error:
    raise RuntimeError(
        f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}"
    ) from error

if result.get("code") != 0:
    raise RuntimeError(result.get("message", "Request failed"))

print(json.dumps(result["data"], ensure_ascii=False, indent=2))

JavaScript: submit once from your server

Save as .mjs and run in a Node.js environment with built-in fetch, using the same environment variables and request JSON. Do not put your key in a frontend component.

import { readFile } from 'node:fs/promises';

const base = process.env.GPT_API_BASE_URL?.replace(/\/+$/, '');
const key = process.env.GPT_API_KEY;
if (!base || !key) throw new Error('Set GPT_API_BASE_URL and GPT_API_KEY');

const payload = await readFile('gptapi-request.json', 'utf8');
const response = await fetch(`${base}/api/ai/generate`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${key}`,
    'Content-Type': 'application/json',
  },
  body: payload,
  signal: AbortSignal.timeout(60000),
});
const result = await response.json();
if (!response.ok || result.code !== 0) {
  throw new Error(
    `HTTP ${response.status}: ${result.message ?? 'Request failed'}`
  );
}
console.log(JSON.stringify(result.data, null, 2));

The client’s 60-second timeout limits waiting for submission, not generation duration. A timeout does not prove the server rejected a task. If no ID arrived, check creation and credit records before contacting support. Running all three generation examples submits three independent tasks; choose one implementation.

Troubleshooting

See error help for authentication, credits, model parameters and task failures. Cross-origin browser generation and task queries require Bearer authentication and credentials: 'omit'. Request catalogs and quotes through your backend. User sk_ keys do not authenticate account-balance endpoints; inspect credits on the website’s account pages.

Developers and API scope

·

Billing

· Contact support