JavaScript (Node.js)

Using our Midjourney API with JavaScript (Node.js)

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 to start generating Midjourney images via API is by getting a demo account (opens in a new tab).

Get the Authentication Token

Animation of steps to generate an authentication token

  1. 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).
  2. After you log in, click your user icon on the bottom left: user icon screenshot for ImagineAPI
  3. These are you user settings. Scroll to the bottom and find the Token field and click the round arrow button to regenerate the token:
  4. 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.:
  5. Then click the checkbox button on the top right to save your account changes: save account details for token

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.

midjourney-api.js
// using fetch — requires Node.js version 18 or higher
 
const data = {
    prompt: "a pretty lady at the beach --ar 9:21 --chaos 40 --stylize 1000"
};
 
// we wrap it in a main function here so we can use async/await inside of it.
async function main() {
    try {
        const response = await fetch('https://cl.imagineapi.dev/items/images/', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer u667iLDO2Xfu0-qpv_nu82EeeDtYGlsf', // <<<< TODO: remember to change this
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
 
        const responseData = await response.json();
        console.log(responseData);
    } catch (error) {
        console.error('Error generating image:', error);
        throw error;
    }
}
 
main();
⚠️

如果 cl.imagineapi.dev 出现超时或者无法工作,请通过微信联系我们 (opens in a new tab),将会有 帮助您解决任何障碍。

We run it using (Node.js 18 or higher is required):

 node --version
v18.14.0
 
 node midjourney-api.js

The output will look like this:

{
  data: {
    id: '7f360434-675f-4abb-8cca-1ca0bca6f1a6',
    prompt: 'a pretty lady at the beach --ar 9:21 --chaos 40 --stylize 1000',
    results: null,
    user_created: '4df804f1-e32e-4e1c-be58-6acbe48cce98',
    date_created: '2023-09-01T03:30:34.094Z',
    status: 'pending',
    progress: null,
    url: null,
    error: null,
    upscaled_urls: null,
    upscaled: [],
    ref: null,
  }
}

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 is pending which is the default when an image generation is first created
  • when it's done generating (status will be completed), upscaled_urls will have 4 separate image urls and url 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 enable so it's usually quite fast.

Let's create a new file to get the image we created in the previous step.

get-image.js
 
const imageId = '7f360434-675f-4abb-8cca-1ca0bca6f1a6'; // <<< TODO: change this to image ID (the ID you got from previous request)
 
async function main() {
  try {
    const response = await fetch(`https://cl.imagineapi.dev/items/images/${imageId}`, {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer u667iLDO2Xfu0-qpv_nu82EeeDtYGlsf', // <<<< TODO: remember to change this
        'Content-Type': 'application/json'
      }
    })
 
    const responseData = await response.json();
    console.log(responseData)
  } catch (error) {
    console.error('Error', error);
    throw error;
  }
}
 
main();

We then run it (Node.js 18 or higher is required):

 node --version
v18.14.0
 
 node get-image.js

And if the image finished generating, this is the results we get:

{
  data: {
    id: '7f360434-675f-4abb-8cca-1ca0bca6f1a6',
    prompt: 'a pretty lady at the beach --ar 9:21 --chaos 40 --stylize 1000',
    results: '1f662f4e-e0f1-4e0f-a6a4-30eac3865ab5',
    user_created: '4df804f1-e32e-4e1c-be58-6acbe48cce98',
    date_created: '2023-09-01T03:30:34.094Z',
    status: 'completed',
    progress: null,
    url: 'https://cl.imagineapi.dev/assets/1f662f4e-e0f1-4e0f-a6a4-30eac3865ab5/1f662f4e-e0f1-4e0f-a6a4-30eac3865ab5.png',
    error: null,
    upscaled_urls: [
      'https://cl.imagineapi.dev/assets/c77e1a16-c3e2-4ea6-b9d7-ab571644d080/c77e1a16-c3e2-4ea6-b9d7-ab571644d080.png',
      'https://cl.imagineapi.dev/assets/018aa788-c140-4851-8c88-5297fe9186c9/018aa788-c140-4851-8c88-5297fe9186c9.png',
      'https://cl.imagineapi.dev/assets/2cfcfa5c-ae91-4921-877a-0366ce4b68da/2cfcfa5c-ae91-4921-877a-0366ce4b68da.png',
      'https://cl.imagineapi.dev/assets/83ef688b-a6a7-46c7-8cb7-756f833037cb/83ef688b-a6a7-46c7-8cb7-756f833037cb.png'
    ],
    upscaled: [
      '018aa788-c140-4851-8c88-5297fe9186c9',
      '2cfcfa5c-ae91-4921-877a-0366ce4b68da',
      '83ef688b-a6a7-46c7-8cb7-756f833037cb',
      'c77e1a16-c3e2-4ea6-b9d7-ab571644d080'
    ],
    ref: null
  }
}

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):

midjourney-api.js
// using fetch — requires Node.js version 18 or higher
 
const data = {
    prompt: "a pretty lady at the beach --ar 9:21 --chaos 40 --stylize 1000"
};
 
// we wrap it in a main function here so we can use async/await inside of it.
async function main() {
    let promptResponseData;
    // generate the image
    try {
        const response = await fetch('https://cl.imagineapi.dev/items/images/', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer u667iLDO2Xfu0-qpv_nu82EeeDtYGlsf', // <<<< TODO: remember to change this
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
 
        promptResponseData = await response.json();
        console.log(promptResponseData);
    } catch (error) {
        console.error('Error generating image:', error);
        throw error;
    }
 
    // check if the image has finished generating
    // let's repeat this code every 5000 milliseconds (5 seconds, set at the bottom)
    const intervalId = setInterval(async function () {
        try {
          console.log('Checking image details');
          const response = await fetch(`https://cl.imagineapi.dev/items/images/${promptResponseData.data.id}`, {
            method: 'GET',
            headers: {
                'Authorization': 'Bearer u667iLDO2Xfu0-qpv_nu82EeeDtYGlsf', // <<<< TODO: remember to change this
                'Content-Type': 'application/json'
            }
          })
 
          const responseData = await response.json();
          if (responseData.data.status === 'completed' || responseData.data.status === 'failed') {
            // stop repeating
            clearInterval(intervalId);
            console.log('Completed image detials', responseData.data);
          } else {
            console.log("Image is not finished generation. Status: ", responseData.data.status)
          }
        } catch (error) {
          console.error('Error getting updates', error);
          throw error;
        }
    }, 5000 /* every 5 seconds */);
    // TODO: add a check to ensure this does not run indefinitely
}
 
main();

Here's how the output might look like:

{
  data: {
    id: 'a930a17c-2877-4ad0-8338-1dfac3ce5a84',
    prompt: 'a pretty lady at the beach --ar 9:21 --chaos 40 --stylize 1000',
    results: null,
    user_created: '4df804f1-e32e-4e1c-be58-6acbe48cce98',
    date_created: '2023-09-01T04:41:18.102Z',
    status: 'pending',
    progress: null,
    url: null,
    error: null,
    upscaled_urls: null,
    upscaled: [],
    ref: null
  }
}
Checking image details
Image is not finished generation. Status:  pending
Checking image details
Image is not finished generation. Status:  pending
Checking image details
Image is not finished generation. Status:  pending
Checking image details
Image is not finished generation. Status:  pending
Checking image details
Image is not finished generation. Status:  in-progress
Checking image details
Image is not finished generation. Status:  in-progress
Checking image details
Image is not finished generation. Status:  in-progress
Checking image details
Image is not finished generation. Status:  in-progress
Checking image details
Image is not finished generation. Status:  in-progress
Checking image details
Image is not finished generation. Status:  in-progress
Checking image details
Completed image detials {
  id: 'a930a17c-2877-4ad0-8338-1dfac3ce5a84',
  prompt: 'a pretty lady at the beach --ar 9:21 --chaos 40 --stylize 1000',
  results: 'b5d1542e-e4a0-4f47-8f61-d9961e7a45f5',
  user_created: '4df804f1-e32e-4e1c-be58-6acbe48cce98',
  date_created: '2023-09-01T04:41:18.102Z',
  status: 'completed',
  progress: null,
  url: 'https://cl.imagineapi.dev/assets/b5d1542e-e4a0-4f47-8f61-d9961e7a45f5/b5d1542e-e4a0-4f47-8f61-d9961e7a45f5.png',
  error: null,
  upscaled_urls: [
    'https://cl.imagineapi.dev/assets/e58eaa77-e5c4-480a-a183-674f139f6591/e58eaa77-e5c4-480a-a183-674f139f6591.png',
    'https://cl.imagineapi.dev/assets/aa7571cb-eb58-4500-911c-77470e0d6032/aa7571cb-eb58-4500-911c-77470e0d6032.png',
    'https://cl.imagineapi.dev/assets/82a8c1f3-664b-438b-befb-9c9fefb1aa73/82a8c1f3-664b-438b-befb-9c9fefb1aa73.png',
    'https://cl.imagineapi.dev/assets/226b80ef-8c42-4c7d-910d-ffd8ea546647/226b80ef-8c42-4c7d-910d-ffd8ea546647.png'
  ],
  upscaled: [
    '226b80ef-8c42-4c7d-910d-ffd8ea546647',
    '82a8c1f3-664b-438b-befb-9c9fefb1aa73',
    'aa7571cb-eb58-4500-911c-77470e0d6032',
    'e58eaa77-e5c4-480a-a183-674f139f6591'
  ],
  ref: null
}
 

And here's what upscaled_urls look like: auto upscaled Midjourney image with Node.js