imageapiai
v1.2.0
Published
Official Node.js SDK for ImageAPI AI - Generate and refine AI images with simple API calls.
Downloads
58
Maintainers
Readme
ImageAPI AI Node.js & TypeScript SDK
Official JavaScript, TypeScript, and Node.js SDK for ImageAPI AI. Generate high-resolution AI images with low latency, refine prompts with 5 free retries, and integrate image generation directly into your apps and automated workflows.
Built with zero external dependencies using native fetch, fully compatible with Node.js (18+), Next.js (App & Pages Router), Cloudflare Workers, Vercel Edge, Bun, and Deno.
⚡ Quick Start
1. Installation
npm install imageapiai
2. Set Your API Key
Get your secret API key (sk_live_...) from the ImageAPI.ai Dashboard.
Set it in your environment:
export IMAGEAPIAI_API_KEY="sk_live_your_api_key_here"
3. Generate an Image in 3 Lines
const ImageAPI = require('imageapiai');
const client = new ImageAPI(); // Automatically reads process.env.IMAGEAPIAI_API_KEY
const res = await client.generate("A futuristic cyberpunk street with neon reflections, 8k render");
console.log(res.data.imageUrl); // or res.data.image_url
🚀 Framework & Platform Integration Examples
Next.js (App Router / Route Handler)
// app/api/generate/route.ts
import { NextResponse } from 'next/server';
import ImageAPI from 'imageapiai';
// Zero-config: picks up IMAGEAPIAI_API_KEY or NEXT_PUBLIC_IMAGEAPIAI_API_KEY
const client = new ImageAPI();
export async function POST(request: Request) {
try {
const { prompt } = await request.json();
const response = await client.generate({
prompt,
width: 1024,
height: 1024,
quality: 'high', // 'low' | 'medium' | 'high'
});
return NextResponse.json({ imageUrl: response.data.imageUrl });
} catch (error: any) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
Express.js Backend
// server.js
const express = require('express');
const ImageAPI = require('imageapiai');
const app = express();
app.use(express.json());
const client = new ImageAPI({
apiKey: process.env.IMAGEAPIAI_API_KEY
});
app.post('/api/create-avatar', async (req, res) => {
try {
const { prompt } = req.body;
const result = await client.generate({
prompt,
width: 512,
height: 512,
quality: 'medium'
});
res.json({
success: true,
imageUrl: result.data.imageUrl,
promptId: result.data.promptId
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
Cloudflare Workers / Edge Functions
// worker.js
import ImageAPI from 'imageapiai';
export default {
async fetch(request, env) {
if (request.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 });
}
const { prompt } = await request.json();
const client = new ImageAPI({ apiKey: env.IMAGEAPIAI_API_KEY });
try {
const result = await client.generate(prompt);
return new Response(JSON.stringify(result), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), { status: 500 });
}
}
};
📖 Features & SDK Methods
1. Generate a Fresh Image
Pass a simple string prompt shorthand, or configure dimensions and inference quality:
// Shorthand string call
const quickRes = await client.generate("An oil painting of a French coastal village");
// Full options call
const customRes = await client.generate({
prompt: "A photo of an astronaut on Mars during golden hour",
width: 1024,
height: 768,
quality: "high" // 'low' | 'medium' (default) | 'high'
});
console.log('Image URL:', customRes.data.imageUrl);
console.log('Credits Deducted:', customRes.data.creditsDeducted);
console.log('Credits Remaining:', customRes.data.creditsRemaining);
2. Refine / Retry an Existing Image (5 Free Retries)
Each generation includes up to 5 free refinement retries that modify the image for 0 credits:
// Refine an existing generation using convenience helper
const refined = await client.refine(
'gen_a1b2c3d4e5f6', // Parent generation/prompt ID
'Add neon rain reflections on the ground and cinematic lighting', // Appended modification
{ quality: 'high' } // Optional dimension/quality overrides
);
console.log('Refined Image URL:', refined.data.imageUrl);
console.log('Retries Left:', refined.data.retriesRemaining);
console.log('Credits Deducted:', refined.data.creditsDeducted); // 0
3. Check Credit Balance & User Profile
Retrieve account status, credit balance, and generation history:
// Fetch account status and credit balance
const profile = await client.getProfile();
console.log('Credit Balance:', profile.data.creditBalance);
console.log('Subscription:', profile.data.subscriptionStatus);
// Fetch image generation history
const history = await client.getHistory();
console.log('Total Generated Images:', history.data.length);
🛠️ Configuration & Shorthands
Auto-Discovery of API Keys
The constructor will automatically check the following environment variables in order if no key is explicitly passed:
process.env.IMAGEAPIAI_API_KEYprocess.env.IMAGEAPI_API_KEYprocess.env.NEXT_PUBLIC_IMAGEAPIAI_API_KEY
// Zero-config (reads from environment variables)
const client = new ImageAPI();
// Or explicit initialization
const client = new ImageAPI({ apiKey: 'sk_live_...' });
// Or raw string key
const client = new ImageAPI('sk_live_...');
Dual-Case Property Normalization
All response fields support both camelCase and snake_case properties to prevent runtime property lookup errors:
data.imageUrl⇄data.image_urldata.promptId⇄data.prompt_iddata.creditsRemaining⇄data.credits_remainingdata.creditsDeducted⇄data.credits_deducteddata.retriesRemaining⇄data.retries_remaining
📚 API & SDK Reference
| Method | Parameters | Description | | ----------------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------- | | new ImageAPI(config?) | string | { apiKey?, baseUrl? } | Initializes client instance with zero-config env fallback. | | client.generate(params) | string | { prompt, width?, height?, quality?, parentPromptId?, promptUpdate? } | Generates a new image or refines an existing one. | | client.refine(parentId, update, options?) | string, string, { width?, height?, quality? } | Refines an image without deducting credits (up to 5 times). | | client.getProfile() | None | Returns account profile, balance, and subscription status. | | client.getHistory() | None | Returns list of historical image generations. |
🔗 Resources
Website: https://imageapiai.com
Dashboard & API Keys: https://imageapiai.com/dashboard
API Documentation: https://imageapiai.com/docs
Showcase Gallery: https://imageapiai.com/showcase
📄 License
MIT © ImageAPI AI
