How to beginner · 3 min read

How to generate images with DALL-E 3

Quick answer
Use the OpenAI API with the dall-e-3 model to generate images by sending a prompt to client.images.generate(). Provide your prompt and desired image size, then retrieve the image URL from the response.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the official openai Python package and set your API key as an environment variable for secure authentication.

bash
pip install openai>=1.0

Step by step

This example shows how to generate an image with dall-e-3 using the OpenAI Python SDK. It sends a prompt and requests a 1024x1024 image, then prints the returned image URL.

python
import os
from openai import OpenAI

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

response = client.images.generate(
    model="dall-e-3",
    prompt="A futuristic city skyline at sunset, vibrant colors, detailed",
    size="1024x1024"
)

image_url = response.data[0].url
print("Generated image URL:", image_url)
output
Generated image URL: https://openai.com/images/generated/abc123.png

Common variations

  • Change size to "256x256" or "512x512" for smaller images.
  • Use asynchronous calls with asyncio and await for non-blocking image generation.
  • Adjust n parameter to generate multiple images per prompt.
  • Use different prompts to explore creative outputs.
python
import os
import asyncio
from openai import OpenAI

async def generate_image_async():
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    response = await client.images.generate(
        model="dall-e-3",
        prompt="A serene mountain lake with reflections, photorealistic",
        size="512x512",
        n=2
    )
    for i, img in enumerate(response.data):
        print(f"Image {i+1} URL:", img.url)

asyncio.run(generate_image_async())
output
Image 1 URL: https://openai.com/images/generated/def456.png
Image 2 URL: https://openai.com/images/generated/ghi789.png

Troubleshooting

  • If you get an authentication error, verify your OPENAI_API_KEY environment variable is set correctly.
  • For rate limit errors, reduce request frequency or check your OpenAI usage quota.
  • If images fail to generate, confirm you are using the correct model name dall-e-3 and valid prompt strings.
  • Network errors may require retry logic or checking your internet connection.

Key Takeaways

  • Use the OpenAI Python SDK's client.images.generate() with dall-e-3 to create images from text prompts.
  • Set your API key securely via environment variables to authenticate requests.
  • Adjust image size and number of images with size and n parameters for flexibility.
  • Async calls enable non-blocking image generation in Python applications.
  • Check model name and API key if you encounter errors during image generation.
Verified 2026-04 · dall-e-3
Verify ↗