Complete Guide to using DALL-E API in Python

Harish GargHarish Garg
2 min read

In this article, we will see how to use and call OpenAI DALL-E API in Python. We will cover how to use Google Colab notebook to call DALL-E API in Python.

We will demonstrate calling DALL-E API in Python for all its features, like new image generation, editing an image, and generating image variations.

Let’s dive in.

Table of Contents

Requirements for calling DALL-E API in Python

You could run all the code from this article locally on your machine too.

However, for demonstration assumes you are using a Google Colab Notebook.

If you are going to run it locally, you need to make sure you have Python 3.x or higher installed.

You also need an OpenAI Account.

Setup

Open up a new Google Colab Notebook.

The rest of the steps below require you to type the code in the Google Colab and execute that particular cell before going to the next step.

Install OpenAI’s Python module by running this code

!pip install openai

Next, we will import the required Python modules. Type and execute the below code in another cell in the Colab.

import os import openai from IPython.display import Image from IPython import display from base64 import b64decode

Let’s set up the OpenAI API or secret key.

Copy your OpenAI API or secret key and paste it between the quotes in the below line

openai.api_key = ""

Now you are ready to make your first call to DALL-E API in Python.

Calling DALL-E API in Python to generate a new image

Run the below code to make your first call to DALL-E API in Python.

response = openai.Image.create( prompt="A cute baby sea otter", n=1, size="256x256", response_format="b64_json" )

This code generates a single variant image for the prompt “a cute sea otter”. You can go ahead and change the prompt to whatever you like.

the response is a JSON object that is stored in the response variable.

If you print the response, you will output it like this.

DALL-E API in Python

We will now use the base64 string that was returned to us by the DALL-E API to display the image in the Google Colab Notebook itself.

First, we extract the base64 string from the response JSON object

image_b64 = response['data'][0]['b64_json']

Now we use this base64 string to display the image in our Google Colab.

display.Image(b64decode(image_b64))

DALL-E API in Python - image display

I will be updating this guide with how to play around with the various parameters in the API calls as well as will cover other features of the API.

Stay tuned.

0
Subscribe to my newsletter

Read articles from Harish Garg directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Harish Garg
Harish Garg