How to Generate Images with an API: Complete Beginner's Guide
I remember my first attempt at generating images with code. I spent three hours wrestling with ImageMagick, installed about twelve dependencies, and ended up with a blurry mess that looked nothing like what I wanted.
There's a better way.
Image generation APIs let you create professional images with a simple HTTP request. No image processing libraries. No complex installations. Just send data, get an image back.
Here's everything you need to know to get started.
What is an image generation apiWhat Is an Image Generation API?
An image generation API is a web service that creates personalized images from templates. You design a template once with placeholder fields, then the API swaps in your data to generate unique images.
Think of it like mail merge, but for images instead of documents. One template, unlimited variations.
Common use cases:
- Social media posts with dynamic text
- E-commerce product images with price overlays
- Personalized certificates and awards
- Blog thumbnails and OG images
- Email headers with recipient names
How it works simple versionHow It Works (Simple Version)
Your App → API Request (with data) → Image API → Returns Image URL
That's it. Three steps:
- Prepare your data - The text, images, or variables you want in your image
- Send a request - Call the API endpoint with your data
- Get your image - Receive a URL or binary image data
Getting started your first imageGetting Started: Your First Image
Let's generate an actual image. I'll use Imejis.io for this tutorial, but the concepts work with any image API.
Step 1 get your api keyStep 1: Get Your API Key
Sign up at imejis.io and grab your API key from the dashboard. The free tier gives you 100 images per month.
Step 2 create or choose a templateStep 2: Create or Choose a Template
Templates are the foundation. They define your image layout with placeholder fields that the API can edit. You have two options:
Option A: Use a public template
- Browse the template library for pre-built designs
- Social posts, certificates, product cards, and more
- Ready to use immediately
Option B: Create your own
- Use the drag-and-drop editor (similar to Figma or Canva)
- Add text, images, shapes, and backgrounds
- Mark specific elements as "editable" so the API can change them
For this example, we'll use a social media template with editable title and subtitle fields.
Step 3 make your first api callStep 3: Make Your First API Call
Here's a basic request:
curl -X POST https://render.imejis.io/v1/your-design-id \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"title": "Hello World!",
"subtitle": "My first API-generated image"
}'The response includes your image URL:
{
"success": true,
"url": "https://cdn.imejis.io/images/abc123.png",
"width": 1200,
"height": 630
}That's your image. Ready to use.
Code examplesCode Examples
NodejsNode.js
const generateImage = async (designId, title, subtitle) => {
const response = await fetch(`https://render.imejis.io/v1/${designId}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.IMEJIS_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ title, subtitle })
});
const result = await response.json();
return result.url;
};
// Usage
const imageUrl = await generateImage(
'social-post-01',
'Product Launch!',
'Available now at 20% off'
);
console.log(imageUrl);PythonPython
import requests
import os
def generate_image(design_id, title, subtitle):
response = requests.post(
f'https://render.imejis.io/v1/{design_id}',
headers={
'Authorization': f'Bearer {os.environ["IMEJIS_API_KEY"]}',
'Content-Type': 'application/json'
},
json={
'title': title,
'subtitle': subtitle
}
)
return response.json()['url']
# Usage
image_url = generate_image(
'social-post-01',
'Product Launch!',
'Available now at 20% off'
)
print(image_url)No code zapierNo-Code (Zapier)
You don't need to write code at all. Connect Imejis.io to Zapier and generate images from:
- New Google Sheets rows
- Form submissions
- E-commerce orders
- CRM updates
Check out our Zapier integration guide for the full setup walkthrough.
Bulk generation the real powerBulk Generation: The Real Power
Creating one image is nice. But the real power is generating thousands of personalized images from your data.
Imagine you have a customer list. One API loop creates unique images for each person:
const customers = [
{ name: 'Sarah', discount: '25%' },
{ name: 'Mike', discount: '30%' },
{ name: 'Lisa', discount: '20%' }
];
const designId = 'promo-email-template';
for (const customer of customers) {
const imageUrl = await generateImage(
designId,
`Hey ${customer.name}!`,
`Your exclusive ${customer.discount} discount awaits`
);
await sendEmail(customer.email, imageUrl);
}Each customer gets a personalized image. No manual design work.
Editable fields template variablesEditable Fields (Template Variables)
When you create a template, you mark certain elements as "editable." These become the fields you can change via API. Common field types:
| Type | Example | Use Case |
|---|---|---|
| Text | {{title}} | Headlines, names, prices |
| Image | {{product_image}} | Photos, logos, avatars |
| Color | {{brand_color}} | Dynamic theming |
| QR Code | {{qr_url}} | Tickets, links |
| Date | {{event_date}} | Timestamps, deadlines |
Your API request fills in these variables. Send a POST to /v1/event-ticket with:
{
"attendee_name": "John Smith",
"event_date": "March 15, 2026",
"seat_number": "A-42",
"qr_url": "https://event.com/ticket/12345"
}Response formatsResponse Formats
Most APIs support multiple output formats:
- URL - Returns a hosted image URL (fastest)
- Base64 - Returns image data encoded as base64
- Binary - Returns raw image bytes
- Webhook - Sends the image to your endpoint when ready
For most use cases, the URL response works best. The image is hosted on a CDN and ready to embed anywhere.
Error handlingError Handling
Things can go wrong. Handle errors gracefully:
const generateImage = async (designId, data) => {
try {
const response = await fetch(`https://render.imejis.io/v1/${designId}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.IMEJIS_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}
return await response.json();
} catch (error) {
console.error('Image generation failed:', error.message);
return null;
}
};Common errors:
- 401 Unauthorized - Check your API key
- 400 Bad Request - Missing required fields
- 429 Rate Limited - Too many requests, slow down
- 404 Not Found - Template ID doesn't exist
Performance tipsPerformance Tips
Cache your imagesCache Your Images
If you're generating the same image multiple times, cache the URL:
const imageCache = new Map();
const getImage = async (designId, data) => {
const cacheKey = JSON.stringify({ designId, data });
if (imageCache.has(cacheKey)) {
return imageCache.get(cacheKey);
}
const imageUrl = await generateImage(designId, data);
imageCache.set(cacheKey, imageUrl);
return imageUrl;
};Use webhooks for batch processingUse Webhooks for Batch Processing
Generating hundreds of images? Use webhooks instead of waiting for each response:
// Send batch request
const response = await fetch('https://render.imejis.io/v1/product-card/batch', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.IMEJIS_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
items: products,
webhook_url: 'https://yoursite.com/webhook/images'
})
});
// Your webhook receives results as they completePre warm templatesPre-warm Templates
For time-sensitive applications, make a dummy request to "warm up" the template before you need it. This ensures the first real request is fast.
What to build nextWhat to Build Next
Now that you know the basics, here are some ideas:
- Dynamic OG images - Generate unique Open Graph images for each blog post
- Personalized emails - Add recipient names to email header images
- Product catalogs - Auto-generate product cards from your database
- Social automation - Create quote graphics with our quote builder
- Certificates - Generate completion certificates for online courses
FaqFAQ
How fast is image generationHow fast is image generation?
Most APIs return images in 200-500ms. Complex templates with multiple layers may take slightly longer.
Can i use my own fontsCan I use my own fonts?
Yes. Upload custom fonts to your account and reference them in templates.
What image formats are supportedWhat image formats are supported?
PNG, JPEG, and WebP are standard. Some APIs also support PDF and SVG.
Is there a size limitIs there a size limit?
Typically up to 4K resolution (4096x4096 pixels). Check your API's documentation for specific limits.
Can i generate images without a templateCan I generate images without a template?
Some APIs support "raw" mode where you define the entire layout in your request. But templates are usually faster and easier to maintain.
Start buildingStart Building
You now know everything you need to generate images with an API. The basics are simple:
- Get an API key
- Choose or create a template
- Send a request with your data
- Use the returned image
Start with something small. Maybe a personalized greeting image or a dynamic blog thumbnail. Once you see how easy it is, you'll find uses everywhere.