Image Generation
Generate images from text prompts using state-of-the-art AI models. Requires payment via x402.
Endpoint
POST /v1/images/generateRequest
Headers
Content-Type: application/jsonBody Parameters
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
prompt | string | Yes | - | Text description of the image to generate (2-3000 characters) |
model | string | No | flux-schnell | Model ID to use for generation. See Available Models |
width | number | No | 1024 | Image width in pixels (128-2048, must be divisible by 64) |
height | number | No | 1024 | Image height in pixels (128-2048, must be divisible by 64) |
numberResults | number | No | 1 | Number of images to generate (1-4) |
negativePrompt | string | No | - | Elements to exclude from the generated image (max 3000 characters) |
steps | number | No | model-dependent | Inference steps for quality control (1-50). Not supported by all models |
guidance | number | No | - | CFG scale for prompt adherence (1-30). Higher values follow prompt more strictly |
seed | number | No | - | Random seed for reproducible results |
Validation Rules
- Dimensions: Both
widthandheightmust be divisible by 64 - Minimum Size: 128Ă—128 pixels
- Maximum Size: 2048Ă—2048 pixels
- Maximum Images: 4 images per request
- Prompt Length: 2 to 3000 characters
- Steps Support: Check model’s
supportsStepsfield before using
Response
Success Response (200 OK)
{
images: [
{
url: string; // CDN URL of the generated image
uuid: string; // Unique identifier for the image
}
];
model: string; // Model ID used for generation
}Payment Response Headers
The response includes an X-Payment-Response header containing payment transaction details:
// Base64-encoded JSON in X-Payment-Response header
{
success: boolean;
transaction: string; // Transaction hash
transactionHash: string; // Alternative transaction hash field
network: string; // Network used (base)
payer: string; // Wallet address that paid
}To access payment details from the browser, ensure your server exposes the header via CORS:
Access-Control-Expose-Headers: x-payment-responseError Responses
| Status Code | Error | Description |
|---|---|---|
| 400 | INVALID_DIMENSIONS | Width/height not divisible by 64, or outside valid range |
| 400 | INVALID_MODEL | Unknown or unsupported model ID |
| 400 | INVALID_PARAMETER | Invalid parameter value (e.g., numberResults > 4) |
| 402 | PAYMENT_REQUIRED | x402 payment authorization needed |
| 500 | INTERNAL_ERROR | Server error during generation |
Examples
Example 1: Simple Generation
Generate a single 512Ă—512 image with default settings.
import { wrapFetchWithPayment } from 'x402-fetch';
import { privateKeyToAccount } from 'viem/accounts';
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
async function generateImage() {
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'a cute cat sitting on a windowsill, photorealistic',
model: 'flux-schnell',
width: 512,
height: 512,
numberResults: 1,
}),
});
const data = await response.json();
console.log('Generated image:', data.images[0].url);
console.log('Image UUID:', data.images[0].uuid);
console.log('Model used:', data.model);
}
generateImage();Example 2: High Resolution Standard Image
Generate a 1024Ă—1024 image, the most common resolution for general use.
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'a serene mountain landscape at sunset, highly detailed',
model: 'flux-schnell',
width: 1024,
height: 1024,
numberResults: 1,
}),
});
const data = await response.json();
console.log('Image URL:', data.images[0].url);Example 3: Multiple Images
Generate 4 variations of the same prompt in a single request.
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'a colorful abstract pattern, geometric shapes',
model: 'flux-schnell',
width: 512,
height: 512,
numberResults: 4,
}),
});
const data = await response.json();
// Process all generated images
data.images.forEach((img, idx) => {
console.log(`Image ${idx + 1}: ${img.url}`);
console.log(`UUID: ${img.uuid}`);
});Example 4: Using Negative Prompts
Improve quality by specifying unwanted elements to exclude.
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'a beautiful portrait of a woman, professional photography',
negativePrompt: 'blurry, distorted, low quality, bad anatomy, ugly',
model: 'flux-schnell',
width: 768,
height: 768,
numberResults: 1,
}),
});
const data = await response.json();
console.log('High-quality image:', data.images[0].url);Example 5: Advanced Quality Control
Use all quality parameters for maximum control over generation.
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'an elegant art deco interior, luxury and sophistication',
negativePrompt: 'modern, minimalist, plain, simple',
model: 'flux-schnell',
width: 1024,
height: 1024,
numberResults: 2,
steps: 10, // Higher quality (if model supports)
guidance: 8.0, // Strong prompt adherence
seed: 12345, // Reproducible results
}),
});
const data = await response.json();
data.images.forEach((img, idx) => {
console.log(`Variation ${idx + 1}: ${img.url}`);
});Example 6: Portrait Orientation
Generate images in portrait format (3:4 aspect ratio).
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'a full body portrait of an astronaut, studio lighting',
model: 'flux-schnell',
width: 768,
height: 1024,
numberResults: 1,
}),
});
const data = await response.json();
console.log('Portrait image:', data.images[0].url);Example 7: Landscape Orientation
Generate images in landscape format (5:3 aspect ratio).
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'a panoramic view of a tropical beach at sunrise',
model: 'flux-schnell',
width: 1280,
height: 768,
numberResults: 1,
}),
});
const data = await response.json();
console.log('Landscape image:', data.images[0].url);Example 8: Reproducible Results with Seed
Use the same seed to generate consistent results across multiple requests.
const seed = 42; // Fixed seed for reproducibility
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'a steampunk robot, brass and copper, intricate details',
model: 'flux-schnell',
width: 1024,
height: 1024,
numberResults: 1,
seed: seed,
}),
});
const data = await response.json();
console.log('Reproducible image:', data.images[0].url);
console.log('Running again with same seed will produce the same image');Example 9: With Cost Estimation
Check the cost before generating images.
// Step 1: Get cost estimate
const estimateRes = await fetch('https://api.x-router.ai/v1/images/estimate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'flux-schnell',
width: 1024,
height: 1024,
numberResults: 1,
}),
});
const estimate = await estimateRes.json();
console.log(`Estimated cost: $${estimate.estimatedCost.usd} USDC`);
// Step 2: Generate with payment
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'your prompt here',
model: 'flux-schnell',
width: 1024,
height: 1024,
numberResults: 1,
}),
});
const data = await response.json();
console.log('Image generated:', data.images[0].url);Best Practices
Image Generation
- Start with estimates: Use the estimate endpoint to check costs before generation
- Test at lower resolutions: Iterate on prompts at 512Ă—512 before generating final high-resolution images
- Use negative prompts: Improve quality by excluding unwanted elements
- Choose appropriate models: See model selection guide for choosing the right model
- Cache generated images: CDN URLs are permanent and can be stored for future use
Quality Optimization
- Be specific: Detailed prompts produce better results
- Use quality keywords: Terms like “highly detailed”, “professional”, “photorealistic” improve output
- Adjust guidance: Higher guidance values (7-10) make the model follow your prompt more closely
- Experiment with steps: Higher step counts generally improve quality (for models that support it)
- Use seeds for iterations: Fix the seed when refining prompts to see consistent changes
Cost Optimization
- Use appropriate resolutions: Don’t generate at 2048×2048 if 1024×1024 meets your needs
- Choose efficient models: Different models have different capabilities and costs
- Batch similar requests: Generate multiple variations in one request when exploring options
Error Handling
async function generateWithErrorHandling() {
try {
const response = await fetchWithPayment('https://api.x-router.ai/v1/images/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prompt: 'a beautiful landscape',
width: 1024,
height: 1024,
}),
});
if (!response.ok) {
const error = await response.json();
throw new Error(`Generation failed: ${error.error}`);
}
const data = await response.json();
return data.images;
} catch (error) {
console.error('Image generation error:', error);
throw error;
}
}Image URLs
Generated images are hosted on a high-performance CDN with the following characteristics:
- Permanent URLs: Images remain accessible indefinitely
- No authentication required: URLs can be shared publicly
- HTTPS delivery: Secure access
- Global distribution: Fast access worldwide
You can:
- Display images directly in
<img>tags - Download and store locally if needed
- Share URLs with users
- Embed in applications
Supported Aspect Ratios
Any aspect ratio is supported as long as both dimensions are divisible by 64 and within the valid range (128-2048). Common aspect ratios include:
- 1:1 (Square): 512Ă—512, 1024Ă—1024, 2048Ă—2048
- 3:4 (Portrait): 768Ă—1024
- 4:3 (Landscape): 1024Ă—768
- 5:3 (Wide): 1280Ă—768
- 16:9 (Widescreen): 1152Ă—640, 1920Ă—1088
- 21:9 (Ultrawide): 1344Ă—576
Payment Integration
The image generation endpoint uses the x402 payment protocol with USDC on Base:
- No ETH required: x402 is gasless for clients
- Automatic pricing: Cost is calculated based on model, resolution, and parameters
- Transaction details: Available in the
X-Payment-Responseheader - Network supported: Base Mainnet
For browser-based applications, ensure your server CORS configuration exposes the payment header:
// Server-side CORS configuration
{
exposedHeaders: ['x-payment-response']
}Related Endpoints
- Available Models - List all available image generation models
- Cost Estimation - Estimate generation costs before payment
- Text Generation - Generate text with AI models
Related Guides
- Image Generation Basics - Getting started with image generation
- Quality Optimization - Techniques for improving image quality
- Model Selection - Choose the right model for your needs