GPT Image 2 API: Complete Developer Guide with Pricing and Examples

GPT Image 2 API: Complete Developer Guide with Pricing and Examples

Integrate GPT Image 2 into your application with this developer guide. Covers API endpoints, request formats, authentication, pricing, rate limits, code examples in Python and TypeScript, and production best practices.

If you're building an e-commerce site that needs product photos on demand, or a marketing platform that generates ad variants at scale, GPT Image 2 gives you a single integration point. It produces photorealistic output, renders text accurately in images, and follows detailed prompts with consistent results.

This guide covers everything developers need to integrate GPT Image 2 through the Kairval API, including authentication, request formats, code examples, and production best practices.

API Overview

The Kairval API provides a unified interface for accessing GPT Image 2 and other AI image generation models. Key capabilities:

  • Text-to-image generation: Create images from text descriptions
  • Image-to-image editing: Transform existing images with text prompts
  • Multiple output formats: PNG, JPG, WebP
  • Various aspect ratios: 1:1, 16:9, 9:16, 4:3, 3:4
  • Batch generation: Generate multiple images in a single request
  • Asynchronous processing: Submit jobs and retrieve results via webhook or polling

Authentication

All API requests require authentication via an API key:

  1. Sign up for a Kairval account at kairval.com
  2. Generate an API key from your dashboard settings
  3. Include the key in the Authorization header of every request
Authorization: Bearer kv_your_api_key_here

Keep your API key secure. Never expose it in client-side code or public repositories. Use environment variables or a secrets manager in production.

Text-to-Image Generation

Endpoint

POST https://api.kairval.com/v1/images/generate

Request Body

{
  "model": "gpt-image-2",
  "prompt": "A modern minimalist workspace with a laptop, coffee cup, and succulent plant on a white desk, soft natural lighting, editorial photography style",
  "aspect_ratio": "16:9",
  "output_format": "png",
  "negative_prompt": "blurry, watermark, low quality"
}

Request Parameters

ParameterTypeRequiredDescription
modelstringYesModel identifier: "gpt-image-2"
promptstringYesText description of the desired image
aspect_ratiostringNoOutput ratio: 1:1, 16:9, 9:16, 4:3, 3:4 (default: 1:1)
output_formatstringNopng, jpg, webp (default: png)
negative_promptstringNoElements to exclude from generation
nintegerNoNumber of images to generate (1-4, default: 1)
seedintegerNoSeed for reproducible generation

Response

{
  "id": "gen_abc123",
  "model": "gpt-image-2",
  "created": 1714713600,
  "data": [
    {
      "url": "https://storage.kairval.com/generated/abc123.png",
      "revised_prompt": "A clean modern workspace..."
    }
  ]
}

The response includes a generation ID, the model used, timestamps, and an array of generated images. Each image includes a temporary URL and the revised prompt (what the model actually used after processing your input).

Code Examples

Python:

import requests
import os

API_KEY = os.environ.get("KAIRVAL_API_KEY")
API_URL = "https://api.kairval.com/v1/images/generate"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

payload = {
    "model": "gpt-image-2",
    "prompt": "A modern office lobby with glass walls, indoor plants, and warm lighting",
    "aspect_ratio": "16:9",
    "output_format": "webp",
    "negative_prompt": "blurry, distorted, low quality"
}

response = requests.post(API_URL, json=payload, headers=headers)
result = response.json()

for image in result["data"]:
    print(f"Image URL: {image['url']}")

TypeScript:

const response = await fetch("https://api.kairval.com/v1/images/generate", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.KAIRVAL_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "gpt-image-2",
    prompt: "A modern office lobby with glass walls, indoor plants, and warm lighting",
    aspect_ratio: "16:9",
    output_format: "webp",
    negative_prompt: "blurry, distorted, low quality",
  }),
});

const result = await response.json();

for (const image of result.data) {
  console.log(`Image URL: ${image.url}`);
}

cURL:

curl -X POST https://api.kairval.com/v1/images/generate \
  -H "Authorization: Bearer $KAIRVAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "A modern office lobby with glass walls, indoor plants, and warm lighting",
    "aspect_ratio": "16:9",
    "output_format": "webp"
  }'

Image-to-Image Editing

GPT Image 2 also supports editing existing images via the API. Upload a source image and provide editing instructions.

Endpoint

POST https://api.kairval.com/v1/images/edit

Request Body

{
  "model": "gpt-image-2",
  "prompt": "Change the background to a tropical beach at sunset",
  "image": "https://example.com/photo.jpg",
  "strength": 0.7,
  "output_format": "png"
}

Additional Parameters

ParameterTypeRequiredDescription
imagestringYesSource image URL or Base64-encoded data
strengthfloatNoTransformation strength 0.0-1.0 (default: 0.8)
promptstringYesEditing instructions

The strength parameter controls how much the model transforms the source image. A value of 0.3 makes subtle changes (lighting adjustments, color grading) while 0.9 allows dramatic transformations (complete style changes, major element additions).

Pricing

GPT Image 2 API pricing on Kairval is credit-based:

PlanCreditsCost per CreditGPT Image 2 Cost
Free50Included
Starter1,000$0.02~50 credits/image
Pro5,000$0.015~50 credits/image
EnterpriseCustomVolume pricingNegotiated

Credit costs per image may vary based on resolution, aspect ratio, and whether image-to-image mode is used. Higher resolutions and larger aspect ratios consume more credits.

Visit the pricing page for current rates and volume discounts. Enterprise customers can contact the Kairval team for custom pricing and SLA arrangements.

Rate Limits

PlanRequests/minuteConcurrent JobsDaily Limit
Free5250
Starter3051,000
Pro1202010,000
EnterpriseCustomCustomCustom

Rate limit information is included in every API response header:

X-RateLimit-Limit: 30
X-RateLimit-Remaining: 27
X-RateLimit-Reset: 1714714200

Error Handling

The API uses standard HTTP status codes:

CodeMeaningAction
200SuccessParse response normally
400Bad RequestCheck request parameters
401UnauthorizedVerify API key
429Rate LimitedImplement exponential backoff, retry after Retry-After header
500Server ErrorRetry with backoff

Error response format:

{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Retry after 60 seconds.",
    "type": "rate_limit_error"
  }
}

Always implement retry logic with exponential backoff for production applications. GPT Image 2 generation can occasionally take longer than expected under high load.

Production Best Practices

Prompt Engineering for APIs

When generating images programmatically, your prompts need to be even more precise than interactive use because there's no human in the loop to evaluate and adjust:

  • Use template strings: Create prompt templates with variable placeholders for subject, style, and settings
  • Validate inputs: Sanitize user-provided prompt text before sending to the API
  • Set quality defaults: Always include quality keywords and negative prompts in your base template
  • Log prompts and results: Track which prompts produce the best outputs for your use case

Image Storage

Generated image URLs from the API are temporary. For production use:

  1. Download immediately: Fetch the image from the returned URL within the TTL window
  2. Store in your own infrastructure: Upload to your CDN, S3 bucket, or image service
  3. Cache aggressively: Store generated images with a content hash for deduplication
  4. Implement cleanup: Remove unused generated images to control storage costs

Async Processing

For high-volume applications, use the asynchronous API:

  1. Submit a generation job
  2. Receive a job ID immediately
  3. Poll for completion or register a webhook callback
  4. Retrieve results when the job completes

This prevents HTTP timeout issues for complex or batch generations and allows your application to handle other work while waiting.

Cost Optimization

  • Use WebP format for web applications: smaller file sizes with minimal quality loss
  • Generate at the minimum required resolution: don't request 4K if you only need 1080p
  • Cache repeated generations: if multiple users request similar images, serve from cache
  • Batch where possible: use the n parameter to generate multiple variations in one request
  • Monitor usage: set up alerts for unusual credit consumption patterns

Available Models

GPT Image 2 is one of many models available through the Kairval API. Other options include:

All models use the same API structure. Switch between them by changing the model parameter in your request body.

Get Started

The fastest path to a working integration:

  1. Sign up for Kairval and generate an API key from your dashboard
  2. Copy a code example from above into your project and set the KAIRVAL_API_KEY environment variable
  3. Review pricing to pick a credit package that matches your expected volume
  4. Add retry logic and image storage before shipping to production

If you want to see what the model can produce before writing code, the GPT Image 2 model page has a live playground and a gallery of example outputs with the prompts that generated them.