Prompt
How do I call an image generation API from Node.js?
Latest observation
Oct 11, 2026
OpenAI APIWeb search: off
To call an image generation API from Node.js, you usually:
- install an HTTP client like
axiosor use built-infetch - send a POST request with your prompt and any image options
- receive either:
- a URL to the generated image, or
- base64 image data
- save or display the result
Example using fetch in Node.js
Node 18+ has fetch built in.
const apiKey = process.env.IMAGE_API_KEY;
async function generateImage() {
const response = await fetch("https://api.example.com/v1/images/generate", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
},
body: JSON.stringify({
prompt: "A futuristic city at sunset",
size: "1024x1024"
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API error ${response.status}: ${errorText}`);
}
const data = await response.json();
console.log(data);
}
generateImage().catch(console.error);
Example using axios
npm install axios
import axios from "axios";
const apiKey = process.env.IMAGE_API_KEY;
async function generateImage() {
const { data } = await axios.post(
"https://api.example.com/v1/images/generate",
{
prompt: "A futuristic city at sunset",
size: "1024x1024"
},
{
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
},
}
);
console.log(data);
}
generateImage().catch(console.error);
If the API returns base64 image data
You can save it to a file:
import fs from "fs";
async function saveImage(base64Data) {
fs.writeFileSync("image.png", Buffer.from(base64Data, "base64"));
}
Common response patterns
1. URL response
{
"imageUrl": "https://..."
}
2. Base64 response
{
"imageBase64": "iVBORw0KGgoAAAANSUhEUgAA..."
}
Tips
- Keep your API key in environment variables
- Check whether the API expects
prompt,model,size, or other fields - Handle rate limits and errors
- Some APIs require polling if generation is asynchronous
If you want, I can show you:
- a complete Node.js example for a specific API like OpenAI, Stability, or Replicate
- how to download the image automatically
- how to build this into an Express route