Using our Midjourney API with Python
Overview
This guide assumes you're using a demo account (opens in a new tab). We'll quickly get started by generating an image and seeing the results. You get to pick which language you use as well.
The best part is that you can copy the code and use it right away!
The easiest way to start generating Midjourney images via API is by getting a demo account (opens in a new tab).
Get the Authentication Token
- Once you buy a demo account (opens in a new tab), you will receive an email username and password. Use that to log into our demo server: https://cl.imagineapi.dev (opens in a new tab).
- After you log in, click your
user icon
on the bottom left: - These are your user settings. Scroll to the bottom and find the
Token
field andclick the round arrow button
to regenerate the token: - This will create a new token that you can use to authorize your API call with, so
copy the token
. You will be using this shortly so keep it around in a file somewhere: - Then
click the checkbox button
on the top right to save your account changes:
That's all. Now we will use the token to authenticate our API calls.
Generating an image
Now that you have your authentication token, you can generate your first image.
import http.client
import json
import pprint
data = {
"prompt": "a pretty lady at the beach --ar 9:21 --chaos 40 --stylize 1000"
}
headers = {
'Authorization': 'Bearer u667iLDO2Xfu0-qpv_nu82EeeDtYGlsf', # <<<< TODO: remember to change this
'Content-Type': 'application/json'
}
conn = http.client.HTTPSConnection("cl.imagineapi.dev")
conn.request("POST", "/items/images/", body=json.dumps(data), headers=headers)
response = conn.getresponse()
response_data = json.loads(response.read().decode('utf-8'))
pprint.pp(response_data)
We run it using Python:
❯ python3 --version
Python 3.11.5
❯ python midjourney_api.py
The output will look like this:
{ 'data': { 'date_created': '2023-09-18T22:34:10.127Z',
'error': None,
'id': 'd85674b8-106a-45b2-9514-04331e80127c',
'progress': None,
'prompt': 'a pretty lady at the beach --ar 9:21 --chaos 40 '
'--stylize 1000',
'results': None,
'status': 'pending',
'upscaled': [],
'upscaled_urls': None,
'url': None,
'user_created': '126353b1-2c3e-42af-9597-b141c0e50fae',
'ref': None}}
Now your prompt will be sent to Midjourney.
A few important details to note:
- The image
id
will remain the same and we can use it to get the data and status of it status
ispending
which is the default when an image generation is first created- when it's done generating (
status
will becompleted
),upscaled_urls
will have 4 separate image urls andurl
will have one grid image that has all four images in it
Let's continue below and get the images that got generated.
Getting the generated image
It will take up to 30 seconds for an image to get generated in the demo server. We're using a Midjourney account with turbo mode enabled so it's usually quite fast.
Let's create a new file to get the image we created in the previous step.
import http.client
import json
import pprint
image_id = 'd85674b8-106a-45b2-9514-04331e80127c' # TODO: change this to image ID (the ID you got from previous request)
connection = http.client.HTTPSConnection("cl.imagineapi.dev")
headers = {
'Authorization': 'Bearer u667iLDO2Xfu0-qpv_nu82EeeDtYGlsf', # TODO: remember to change this
'Content-Type': 'application/json'
}
try:
connection.request("GET", f"/items/images/{image_id}", headers=headers)
response = connection.getresponse()
data = json.loads(response.read().decode())
pprint.pp(data, indent=4)
except Exception as error:
print(f"Error: {error}")
To run the Python script:
$ python3 --version
Python 3.11.5
$ python3 get_image.py
The expected output when the image has finished generating:
{'data': {'id': 'd85674b8-106a-45b2-9514-04331e80127c',
'prompt': 'a pretty lady at the beach --ar 9:21 --chaos 40 --stylize '
'1000',
'results': 'c167ecef-6f7c-4b94-8aba-6da282c14246',
'user_created': '126353b1-2c3e-42af-9597-b141c0e50fae',
'date_created': '2023-09-18T22:42:52.569Z',
'status': 'completed',
'progress': None,
'url': 'https://cl.imagineapi.dev/assets/c167ecef-6f7c-4b94-8aba-6da282c14246/c167ecef-6f7c-4b94-8aba-6da282c14246.png',
'error': None,
'upscaled_urls': ['https://cl.imagineapi.dev/assets/05f05786-af1a-497e-9a7e-d0aa2add04a7/05f05786-af1a-497e-9a7e-d0aa2add04a7.png',
'https://cl.imagineapi.dev/assets/20984abb-a4a1-4376-b622-178ade59af14/20984abb-a4a1-4376-b622-178ade59af14.png',
'https://cl.imagineapi.dev/assets/c1f1be14-dcb8-4d34-9e4f-3e7fa9e58187/c1f1be14-dcb8-4d34-9e4f-3e7fa9e58187.png',
'https://cl.imagineapi.dev/assets/d82b5c66-7eca-406f-a210-cb645f06c936/d82b5c66-7eca-406f-a210-cb645f06c936.png'],
'upscaled': ['05f05786-af1a-497e-9a7e-d0aa2add04a7',
'20984abb-a4a1-4376-b622-178ade59af14',
'c1f1be14-dcb8-4d34-9e4f-3e7fa9e58187',
'd82b5c66-7eca-406f-a210-cb645f06c936'],
'ref': None}}
This is great, but it would be nice to have the script automatically check the image and show us when it's done.
Waiting for the image automatically
Let's take the code snippet where the image is generated and make it check every 5 seconds to see if the image has been generated (i.e. status
is completed
or failed
):
import json
import time
import http.client
import pprint
data = {
"prompt": "a pretty lady at the beach --ar 9:21 --chaos 40 --stylize 1000"
}
headers = {
'Authorization': 'Bearer u667iLDO2Xfu0-qpv_nu82EeeDtYGlsf', # <<<< TODO: remember to change this
'Content-Type': 'application/json'
}
def send_request(method, path, body=None, headers={}):
conn = http.client.HTTPSConnection("cl.imagineapi.dev")
conn.request(method, path, body=json.dumps(body) if body else None, headers=headers)
response = conn.getresponse()
data = json.loads(response.read().decode())
conn.close()
return data
prompt_response_data = send_request('POST', '/items/images/', data, headers)
pprint.pp(prompt_response_data)
def check_image_status():
response_data = send_request('GET', f"/items/images/{prompt_response_data['data']['id']}", headers=headers)
if response_data['data']['status'] in ['completed', 'failed']:
print('Completed image details',)
pprint.pp(response_data['data'])
return True
else:
print(f"Image is not finished generation. Status: {response_data['data']['status']}")
return False
while not check_image_status():
time.sleep(5) # wait for 5 seconds
Here's how the output might look like:
{'data': {'id': '14d1bc7c-076f-4c7a-bb06-7ca2c8cad5f5',
'prompt': 'a pretty lady at the beach --ar 9:21 --chaos 40 --stylize '
'1000',
'results': None,
'user_created': '126353b1-2c3e-42af-9597-b141c0e50fae',
'date_created': '2023-09-19T04:17:33.217Z',
'status': 'pending',
'progress': None,
'url': None,
'error': None,
'upscaled_urls': None,
'upscaled': [],
'ref': None}}
Image is not finished generation. Status: pending
Image is not finished generation. Status: pending
Image is not finished generation. Status: pending
Image is not finished generation. Status: pending
Image is not finished generation. Status: pending
Image is not finished generation. Status: in-progress
Image is not finished generation. Status: in-progress
Image is not finished generation. Status: in-progress
Image is not finished generation. Status: in-progress
Image is not finished generation. Status: in-progress
Completed image details
{'id': '14d1bc7c-076f-4c7a-bb06-7ca2c8cad5f5',
'prompt': 'a pretty lady at the beach --ar 9:21 --chaos 40 --stylize 1000',
'results': '213d371e-0dd8-479e-8ae8-2fd631f9164b',
'user_created': '126353b1-2c3e-42af-9597-b141c0e50fae',
'date_created': '2023-09-19T04:17:33.217Z',
'status': 'completed',
'progress': None,
'url': 'https://cl.imagineapi.dev/assets/213d371e-0dd8-479e-8ae8-2fd631f9164b/213d371e-0dd8-479e-8ae8-2fd631f9164b.png',
'error': None,
'upscaled_urls': ['https://cl.imagineapi.dev/assets/fccd79d5-3a1f-4756-b54c-98f23e390ab0/fccd79d5-3a1f-4756-b54c-98f23e390ab0.png',
'https://cl.imagineapi.dev/assets/c3fa377d-7eb1-468a-bd66-40a5da42ea76/c3fa377d-7eb1-468a-bd66-40a5da42ea76.png',
'https://cl.imagineapi.dev/assets/f40c11b4-ed64-4bb4-bf82-3e80039c9ed2/f40c11b4-ed64-4bb4-bf82-3e80039c9ed2.png',
'https://cl.imagineapi.dev/assets/62c701f6-a7c7-4825-ac7f-5ed292c411f9/62c701f6-a7c7-4825-ac7f-5ed292c411f9.png'],
'upscaled': ['62c701f6-a7c7-4825-ac7f-5ed292c411f9',
'c3fa377d-7eb1-468a-bd66-40a5da42ea76',
'f40c11b4-ed64-4bb4-bf82-3e80039c9ed2',
'fccd79d5-3a1f-4756-b54c-98f23e390ab0'],
'ref': None}
And here's what upscaled_urls
look like: