To generate an image, you need to create an account and API key if you haven’t already. You can learn more about this in my tutorial here: π
β Recommended: OpenAI API Getting Started
Do you have an API key? Great!
To generate an image with DALLΒ·E copy&paste the following code and replace your API key and the string description of the image to be generated (prompt
)
import os import openai # Your API Key Here: π openai.api_key = 'sk-XXXXXXXXXXXXXXXXXXXXXXXXXXX' # Your Image Prompt Here: π prompt = "An oil painting of a dancing robot in the style of Monet" response = openai.Image.create( prompt=prompt, n=1, size="256x256", ) print(response["data"][0]["url"])
The output is a URL from where you can download the image:

https://oaidalleapiprodscus.blob.core.windows.net/private/org-CR1YqwB9GAtSsAKHpN1935Dy/user-57ZUj7285WTxwzVJdiweq6JS/img-n9aRtAjhyJMeOzZTXztvkGGD.png?st=2023-04-25T07%3A19%3A14Z&se=2023-04-25T09%3A19%3A14Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-04-25T08%3A17%3A09Z&ske=2023-04-26T08%3A17%3A09Z&sks=b&skv=2021-08-06&sig=57InZSNLylU1peJpPN8yynKvbiKBaLqhVn3l5c9oOSk%3D
You can change the size, e.g., to 1000×1000 pixels — but it’ll cost you more and takes longer:
# ... response = openai.Image.create( prompt=prompt, n=1, size="1024x1024", ) # ...

Here’s the pricing table by the way from the official API page:
Resolution | Price |
1024Γ1024 | $0.020 / image |
512Γ512 | $0.018 / image |
256Γ256 | $0.016 / image |
Yeah, this article just cost me $0.054. π±
π Recommended: Best 35 Helpful ChatGPT Prompts for Coders (2023)

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.