Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To generate an image in one authenticated OpenAI API request, send a prompt to the Images API using a GPT Image model, then decode the base64 image data in the response. For a direct image-generation task, this is the simplest route. Use the Responses API when image creation belongs inside a larger conversational or tool workflow.

Choose the one-request path

Both APIs can produce an image through a single request, but they return it in different shapes and suit different application flows.

Option Best suited to How to handle the result Progress
Images API A direct prompt-to-image request or image editing task Read the image payload from the response data array. GPT Image models return base64 in b64_json by default. Use image streaming where supported if you need incremental progress.
Responses API image-generation tool Image creation that is part of a broader model response, conversation, or tool workflow Inspect the response items and image-generation call; the completed event contains final image data. Streaming can emit generating and completed events.

For a standalone image endpoint, choose Images API. The Responses API is useful when the same interaction needs model orchestration or conversation context. It adds response-item handling that a direct image call does not require.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set up credentials and the SDK

Create an API key in the OpenAI developer platform and store it in a server-side environment variable. Do not put the key in browser JavaScript, a mobile app bundle, or public source control: client-visible credentials can be copied and abused. The OpenAI quickstart describes the basic key, SDK, and request setup.

  1. Install the official SDK for your language, or use HTTPS directly.
  2. Set OPENAI_API_KEY in the environment of the server or job that will make the request.
  3. Send the prompt and selected model to the Images API.
  4. Decode the returned base64 string into bytes, then save, store, or serve those bytes as an image.

Keep the image-generation call behind your own application endpoint if a browser user needs to trigger it. Your server can authenticate with OpenAI, validate prompt and output options, and return the resulting image or a controlled error to the browser.

Make a direct Images API request

Python example

Install the SDK with pip install openai, set OPENAI_API_KEY, then run:

import base64
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

result = client.images.generate(
    model="gpt-image-1",
    prompt="A small glass greenhouse on a rainy city rooftop at blue hour, editorial illustration",
    size="1024x1024",
    quality="medium",
    output_format="png",
)

image_bytes = base64.b64decode(result.data[0].b64_json)
with open("image.png", "wb") as image_file:
    image_file.write(image_bytes)

print("Saved image.png")

The request is one API call. Decoding and writing the response locally are application-side steps, not additional OpenAI requests. Choose a GPT Image model listed in the current model catalog; the catalog includes gpt-image-1 and gpt-image-1-mini as image-generation models.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Raw HTTPS request

If you do not use an SDK, send JSON to the Images endpoint with a bearer key. This shell example requires curl and jq; it saves the base64 payload as a PNG.

curl https://api.openai.com/v1/images/generations 
  -H "Authorization: Bearer $OPENAI_API_KEY" 
  -H "Content-Type: application/json" 
  -d '{
    "model": "gpt-image-1",
    "prompt": "A small glass greenhouse on a rainy city rooftop at blue hour, editorial illustration",
    "size": "1024x1024",
    "quality": "medium",
    "output_format": "png"
  }' | jq -r '.data[0].b64_json' | base64 --decode > image.png

On systems where the base64 utility uses a different decode flag, use that system’s equivalent. In production, parse the HTTP status and JSON response before decoding rather than piping an error response into the image file.

Get the image bytes and choose output options

GPT Image responses contain a data array, with the image represented as base64 in b64_json by default. Base64 is text encoding of the binary image bytes; decode it before treating the result as a PNG, WebP, or JPEG file. Do not write the base64 characters directly to a file with an image extension.

The Images API reference documents controls including:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • size: documented sizes include 1024x1024, 1024x1536, and 1536x1024. Available dimensions can depend on the model and endpoint version; verify the current reference before relying on a custom size.
  • quality: documented values include low, medium, and high, with additional model-dependent values. Higher quality may suit final assets; a lower setting can be appropriate when iterating quickly. Check model-specific support.
  • background: documented choices include transparent, opaque, and auto. Use transparent when the downstream design needs an alpha background and the selected model supports it.
  • output_format: documented formats include PNG, WebP, and JPEG. Choose based on the receiving system’s compatibility and file-handling requirements.

Parameters are not interchangeable across every model. Validate the supported combination in the Images API reference before baking it into a long-lived integration.

When a URL response is relevant

The default GPT Image response is base64 image data. The API reference describes URL responses for DALL·E when response_format is set to url. That distinction matters: do not assume a GPT Image request will return a hosted URL simply because another image model or endpoint has done so.

Use the Responses API when image generation is part of a larger response

The Responses API can let a model invoke an image-generation tool within a broader response flow. This is a better fit when the request includes conversational context or additional model/tool orchestration; a simple prompt-to-file task generally has less response handling with Images API.

For a non-streaming integration, submit one Responses API request with the image-generation tool enabled and inspect the returned output items for the image-generation call and final image data. The exact tool schema and fields can vary with API updates, so use the current image generation guide rather than copying an old payload shape.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If a user interface needs visible progress, enable streaming and handle image-generation events. The streaming reference defines response.image_generation_call.generating and completed events; it also documents image_generation.partial_image events with base64 payloads and an image_generation.completed event containing final base64 image data. Streaming changes how the client receives progress; it does not require a separate image-generation request.

Common errors and fixes

  • 401 or authentication failure: confirm the server process actually has OPENAI_API_KEY, that the key is valid, and that the request sends it as a bearer credential. Never “fix” this by embedding the secret in frontend code.
  • Unsupported parameter or size: check the chosen model’s accepted values for size, quality, background, and output_format. Remove optional parameters one at a time to identify a conflicting setting.
  • Missing image field: first inspect the HTTP status and full error JSON. If the request succeeded, inspect the response shape before assuming data[0].b64_json exists; response forms differ by model and API route.
  • Corrupt or unopenable image: ensure the base64 value was decoded to binary bytes, and that the filename extension matches the requested format. Avoid writing JSON or encoded text as though it were image data.
  • Shell pipeline produces an empty file: the API may have returned an error body rather than image data, or jq may not have found the field. Capture the response to a temporary file, check its status and JSON, then decode only after confirming the expected property exists.
  • No progress events appear: generating and partial-image events require a streaming flow and supported event handling. A normal non-streaming request returns its result without those intermediate notifications.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Reliability, latency, cost, and data handling

A one-request design reduces application orchestration, but it does not make generation instantaneous or eliminate the need to handle failed HTTP requests. Set a reasonable client timeout, check status codes, and surface errors rather than returning a blank image. For production workloads, use bounded retries only for transient failures and avoid retrying blindly when an earlier request may have completed; duplicate generation can mean duplicate usage.

Image dimensions, quality, and output format affect payload size and downstream storage or transfer. Choose the smallest dimensions and quality that meet the use case, especially when users will generate multiple variants. Current model pricing and limits can change; consult the current official API pricing and model documentation before estimating a recurring budget. The referenced API materials do not establish a universal generation time or a fixed price for every parameter combination.

For data-retention planning, OpenAI’s data controls documentation states that /v1/images image generation is Zero Data Retention compatible for gpt-image-1 and gpt-image-1-mini, but not for dall-e-3 or dall-e-2. This is a compatibility statement, not a blanket promise that every account, request, or product configuration has the same retention settings. Review the current data controls applicable to your organization.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The model catalog snapshot identifies DALL·E 2 and DALL·E 3 as deprecated entries. For new work, check the current catalog and migration guidance rather than starting a new integration on a deprecated model.

Or skip the browser setup

If your actual need is a screenshot of a website rather than a newly generated illustration, ScreenshotNeo is a website screenshot API and MCP server: one GET request with a URL returns a PNG, JPEG, WebP, or PDF. It is a different task from generating an image from a prompt.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. It accepts cookie/consent banners and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; those steps can each be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers state the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for AI agents. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo free: 1,000 screenshots a month, no card required.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which API should you use?

Use Images API for a direct prompt-to-image call whose output your application will decode and save. Choose the Responses API image-generation tool when image creation belongs inside a larger conversational or tool-mediated exchange, especially if streaming progress matters. In either case, keep credentials server-side, validate model-specific options, and handle the returned image data according to its actual response format.

Frequently Asked Questions

Can one API request generate more than one image?

The exact number of images supported per request depends on the current endpoint and model parameters; check the Images API reference for the selected model before designing batch behavior.

Can the generated image be returned directly to a web page?

Yes. Your server can return decoded image bytes with the appropriate content type, or store the file and provide an application-controlled URL. Keep the OpenAI key on the server.

Does the Responses API return partial images automatically?

No. Partial-image and progress events are part of a streaming flow; a regular non-streaming call returns without those intermediate events.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.