API Testing Guide
Local testing examples for the image generation API
API Testing Guide
This document provides various code examples for testing the image generation API locally.
Prerequisites
- API Key: Get your API key from the dashboard
- Base URL:
http://localhost:3000(for local testing) or your production URL - Endpoint:
/api/ai/nano-banana/generate
Environment Setup
# Set your API key as environment variable
export API_KEY="sk-your-api-key-here"
export BASE_URL="http://localhost:3000"Basic Examples
1. cURL - Simple Text-to-Image
curl -X POST "${BASE_URL}/api/ai/nano-banana/generate" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A beautiful sunset over mountains",
"size": "1k"
}'2. cURL - High Quality (4K)
curl -X POST "${BASE_URL}/api/ai/nano-banana/generate" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A futuristic city with flying cars",
"size": "4k"
}'3. cURL - With Aspect Ratio
curl -X POST "${BASE_URL}/api/ai/nano-banana/generate" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A wide landscape with mountains and lakes",
"size": "2k",
"aspectRatio": "16:9"
}'4. cURL - With Image URL Reference
curl -X POST "${BASE_URL}/api/ai/nano-banana/generate" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Transform this image into a watercolor painting",
"size": "2k",
"image": "https://example.com/reference-image.jpg"
}'5. cURL - With Multiple Image URLs
curl -X POST "${BASE_URL}/api/ai/nano-banana/generate" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Combine these images into a collage",
"size": "2k",
"image": [
"https://example.com/image1.jpg",
"https://example.com/image2.jpg",
"https://example.com/image3.jpg"
]
}'6. cURL - Upload Local Image (Multipart)
curl -X POST "${BASE_URL}/api/ai/nano-banana/generate" \
-H "Authorization: Bearer ${API_KEY}" \
-F "prompt=Transform this into anime style" \
-F "size=2k" \
-F "image=@/path/to/your/image.jpg"7. cURL - Upload Multiple Local Images
curl -X POST "${BASE_URL}/api/ai/nano-banana/generate" \
-H "Authorization: Bearer ${API_KEY}" \
-F "prompt=Create a composition from these images" \
-F "size=4k" \
-F "aspectRatio=16:9" \
-F "image=@/path/to/image1.jpg" \
-F "image=@/path/to/image2.jpg" \
-F "image=@/path/to/image3.jpg"JavaScript/Node.js Examples
8. Node.js - Simple Request
const API_KEY = 'sk-your-api-key-here';
const BASE_URL = 'http://localhost:3000';
async function generateImage() {
const response = await fetch(`${BASE_URL}/api/ai/nano-banana/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: 'A beautiful sunset over mountains',
size: '1k',
}),
});
const data = await response.json();
console.log('Generated images:', data.images);
return data;
}
generateImage().catch(console.error);9. Node.js - With Error Handling
const API_KEY = 'sk-your-api-key-here';
const BASE_URL = 'http://localhost:3000';
async function generateImageWithErrorHandling(prompt, size = '2k') {
try {
const response = await fetch(`${BASE_URL}/api/ai/nano-banana/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt, size }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(`API Error (${response.status}): ${error.error || 'Unknown error'}`);
}
const data = await response.json();
console.log(`✓ Generated ${data.images.length} image(s)`);
data.images.forEach((img, index) => {
console.log(` Image ${index + 1}: ${img.url}`);
});
return data;
} catch (error) {
console.error('Failed to generate image:', error.message);
throw error;
}
}
// Usage
generateImageWithErrorHandling('A futuristic city at night', '4k')
.catch(console.error);10. Node.js - Upload Local Image (FormData)
const fs = require('fs');
const FormData = require('form-data');
const fetch = require('node-fetch');
const API_KEY = 'sk-your-api-key-here';
const BASE_URL = 'http://localhost:3000';
async function generateWithImage(prompt, imagePath, size = '2k') {
const formData = new FormData();
formData.append('prompt', prompt);
formData.append('size', size);
formData.append('image', fs.createReadStream(imagePath));
const response = await fetch(`${BASE_URL}/api/ai/nano-banana/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
...formData.getHeaders(),
},
body: formData,
});
if (!response.ok) {
const error = await response.json();
throw new Error(`API Error: ${error.error}`);
}
return await response.json();
}
// Usage
generateWithImage(
'Transform this into anime style',
'./test-image.jpg',
'2k'
).then(data => {
console.log('Success:', data.images[0].url);
}).catch(console.error);11. Node.js - Multiple Images with Retry Logic
const API_KEY = 'sk-your-api-key-here';
const BASE_URL = 'http://localhost:3000';
async function generateWithRetry(prompt, options = {}, maxRetries = 3) {
const { size = '2k', aspectRatio, imageUrls = [] } = options;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
console.log(`Attempt ${attempt}/${maxRetries}...`);
const response = await fetch(`${BASE_URL}/api/ai/nano-banana/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt,
size,
aspectRatio,
image: imageUrls.length === 1 ? imageUrls[0] : imageUrls,
}),
});
if (!response.ok) {
const error = await response.json();
// Don't retry on client errors (4xx)
if (response.status >= 400 && response.status < 500) {
throw new Error(`Client error: ${error.error}`);
}
throw new Error(`Server error: ${error.error}`);
}
const data = await response.json();
console.log('✓ Success!');
return data;
} catch (error) {
console.error(`Attempt ${attempt} failed:`, error.message);
if (attempt === maxRetries) {
throw new Error(`Failed after ${maxRetries} attempts: ${error.message}`);
}
// Wait before retrying (exponential backoff)
const delay = Math.pow(2, attempt) * 1000;
console.log(`Waiting ${delay}ms before retry...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// Usage
generateWithRetry('A beautiful landscape', {
size: '4k',
aspectRatio: '16:9',
imageUrls: ['https://example.com/reference.jpg'],
}).then(data => {
console.log('Generated:', data.images);
}).catch(console.error);Python Examples
12. Python - Simple Request
import requests
import os
API_KEY = os.getenv('API_KEY', 'sk-your-api-key-here')
BASE_URL = os.getenv('BASE_URL', 'http://localhost:3000')
def generate_image(prompt, size='1k'):
url = f'{BASE_URL}/api/ai/nano-banana/generate'
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json',
}
data = {
'prompt': prompt,
'size': size,
}
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
result = response.json()
print(f"Generated {len(result['images'])} image(s)")
for i, img in enumerate(result['images']):
print(f" Image {i+1}: {img['url']}")
return result
# Usage
if __name__ == '__main__':
generate_image('A beautiful sunset over mountains', '2k')13. Python - With Error Handling
import requests
import sys
API_KEY = 'sk-your-api-key-here'
BASE_URL = 'http://localhost:3000'
def generate_image_safe(prompt, size='2k', aspect_ratio=None):
url = f'{BASE_URL}/api/ai/nano-banana/generate'
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json',
}
payload = {
'prompt': prompt,
'size': size,
}
if aspect_ratio:
payload['aspectRatio'] = aspect_ratio
try:
response = requests.post(url, headers=headers, json=payload, timeout=60)
if response.status_code == 401:
print('Error: Invalid API key', file=sys.stderr)
return None
elif response.status_code == 402:
print('Error: Insufficient credits', file=sys.stderr)
return None
elif response.status_code == 400:
error_data = response.json()
print(f'Error: {error_data.get("error", "Bad request")}', file=sys.stderr)
return None
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
print('Error: Request timeout', file=sys.stderr)
return None
except requests.exceptions.RequestException as e:
print(f'Error: {str(e)}', file=sys.stderr)
return None
# Usage
result = generate_image_safe('A futuristic city', '4k', '16:9')
if result:
print('Success!')
for img in result['images']:
print(f"URL: {img['url']}")14. Python - Upload Local Image
import requests
API_KEY = 'sk-your-api-key-here'
BASE_URL = 'http://localhost:3000'
def generate_with_image(prompt, image_path, size='2k'):
url = f'{BASE_URL}/api/ai/nano-banana/generate'
headers = {
'Authorization': f'Bearer {API_KEY}',
}
with open(image_path, 'rb') as image_file:
files = {
'image': ('image.jpg', image_file, 'image/jpeg'),
}
data = {
'prompt': prompt,
'size': size,
}
response = requests.post(url, headers=headers, data=data, files=files)
response.raise_for_status()
return response.json()
# Usage
result = generate_with_image(
'Transform this into anime style',
'./test-image.jpg',
'2k'
)
print(f"Generated: {result['images'][0]['url']}")15. Python - Multiple Images with Progress
import requests
from typing import List, Optional
API_KEY = 'sk-your-api-key-here'
BASE_URL = 'http://localhost:3000'
def generate_with_multiple_images(
prompt: str,
image_urls: List[str],
size: str = '2k',
aspect_ratio: Optional[str] = None
):
url = f'{BASE_URL}/api/ai/nano-banana/generate'
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json',
}
payload = {
'prompt': prompt,
'size': size,
'image': image_urls if len(image_urls) > 1 else image_urls[0],
}
if aspect_ratio:
payload['aspectRatio'] = aspect_ratio
print(f"Generating with {len(image_urls)} reference image(s)...")
response = requests.post(url, headers=headers, json=payload, timeout=120)
if not response.ok:
error = response.json()
raise Exception(f"API Error ({response.status_code}): {error.get('error')}")
result = response.json()
print(f"✓ Generated {len(result['images'])} image(s)")
return result
# Usage
image_refs = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg',
]
result = generate_with_multiple_images(
'Create a beautiful composition from these images',
image_refs,
size='4k',
aspect_ratio='16:9'
)
for i, img in enumerate(result['images']):
print(f"Image {i+1}: {img['url']}")Response Format
Success Response
{
"model": "nano-banana-2-4k",
"created": 1705123456,
"images": [
{
"url": "https://example.com/generated-image.png"
}
]
}Error Response
{
"error": "Error message description"
}Error Codes Reference
| Status Code | Error | Description |
|---|---|---|
| 400 | Bad Request | Missing required parameters or invalid input |
| 401 | Unauthorized | Invalid or missing API key |
| 402 | Payment Required | Insufficient credits |
| 500 | Internal Server Error | Server-side error occurred |
Common Error Messages
"Prompt is required"- The prompt parameter is missing or empty"Unauthorized"- API key is invalid or not provided"Insufficient credits"- Account doesn't have enough credits"Too many images, maximum is X"- Exceeded image limit for your plan"Image size should be less than 2.5MB"- Uploaded image is too large"Invalid file type, image required"- Uploaded file is not an image"Failed to generate images"- Generic server error
Parameters Reference
Required Parameters
- prompt (string): Text description of the image to generate
Optional Parameters
-
size (string): Quality level -
"1k","2k", or"4k"(default:"4k")1k/2k: Usesnano-banana-2model (1 credit)4k: Usesnano-banana-2-4kmodel (1.5 credits)
-
aspectRatio (string): Image aspect ratio
- Examples:
"1:1","16:9","9:16","4:3","3:4" - Default:
"auto"(model decides)
- Examples:
-
model (string): Model name (auto-selected based on size)
"nano-banana-2"for 1k/2k quality"nano-banana-2-4k"for 4k quality
-
image (string | string[] | File | File[]): Reference image(s)
- Single URL:
"https://example.com/image.jpg" - Multiple URLs:
["url1", "url2", "url3"] - File upload: Use multipart/form-data
- Max images: 3 (Free), 8 (Pro), 14 (Pro Plus)
- Max file size: 2.5MB per image
- Single URL:
Best Practices
1. Always Use HTTPS in Production
# Development
BASE_URL="http://localhost:3000"
# Production
BASE_URL="https://your-domain.com"2. Store API Keys Securely
# Use environment variables
export API_KEY="sk-your-api-key-here"
# Never hardcode in source code
# ❌ Bad: const API_KEY = "sk-abc123..."
# ✅ Good: const API_KEY = process.env.API_KEY3. Implement Retry Logic
// Retry on 5xx errors, not on 4xx errors
if (response.status >= 500) {
// Retry with exponential backoff
} else if (response.status >= 400) {
// Don't retry, handle error
}4. Handle Timeouts
# Set appropriate timeout values
response = requests.post(url, json=data, timeout=60)5. Validate Images Before Upload
// Check file size
if (file.size > 2.5 * 1024 * 1024) {
throw new Error('Image too large');
}
// Check file type
if (!file.type.startsWith('image/')) {
throw new Error('Invalid file type');
}Common Issues
Issue: "Unauthorized" Error
Cause: Invalid or missing API key
Solution:
# Check your API key format
echo $API_KEY
# Should start with "sk-"
# Verify Authorization header
curl -H "Authorization: Bearer $API_KEY" ...Issue: "Insufficient credits" Error
Cause: Account has run out of credits
Solution:
- Check your credit balance in the dashboard
- Purchase more credits or upgrade your plan
- Note: 1k/2k quality costs 1 credit, 4k costs 1.5 credits
Issue: "Too many images" Error
Cause: Exceeded image limit for your plan
Solution:
- Free plan: Max 3 images
- Pro plan: Max 8 images
- Pro Plus plan: Max 14 images
- Reduce the number of reference images or upgrade your plan
Issue: Request Timeout
Cause: Image generation takes longer than expected
Solution:
# Increase timeout value
response = requests.post(url, json=data, timeout=120) # 2 minutesQuick Test Scripts
Bash Script - Complete Test Suite
#!/bin/bash
API_KEY="${API_KEY:-sk-your-api-key-here}"
BASE_URL="${BASE_URL:-http://localhost:3000}"
echo "=== API Testing Suite ==="
echo "Base URL: $BASE_URL"
echo "API Key: ${API_KEY:0:10}..."
echo ""
# Test 1: Simple generation
echo "Test 1: Simple text-to-image (1k quality)"
curl -s -X POST "$BASE_URL/api/ai/nano-banana/generate" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt":"A beautiful sunset","size":"1k"}' | jq '.'
echo ""
# Test 2: High quality
echo "Test 2: High quality generation (4k)"
curl -s -X POST "$BASE_URL/api/ai/nano-banana/generate" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt":"A futuristic city","size":"4k"}' | jq '.'
echo ""
# Test 3: With aspect ratio
echo "Test 3: With aspect ratio (16:9)"
curl -s -X POST "$BASE_URL/api/ai/nano-banana/generate" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt":"Wide landscape","size":"2k","aspectRatio":"16:9"}' | jq '.'
echo ""
# Test 4: Error handling (missing prompt)
echo "Test 4: Error handling (missing prompt)"
curl -s -X POST "$BASE_URL/api/ai/nano-banana/generate" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"size":"1k"}' | jq '.'
echo ""
echo "=== Tests Complete ==="Python Script - Complete Test Suite
#!/usr/bin/env python3
import requests
import os
import sys
API_KEY = os.getenv('API_KEY', 'sk-your-api-key-here')
BASE_URL = os.getenv('BASE_URL', 'http://localhost:3000')
def test_api(name, payload):
print(f"\n{'='*50}")
print(f"Test: {name}")
print(f"{'='*50}")
try:
response = requests.post(
f'{BASE_URL}/api/ai/nano-banana/generate',
headers={
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json',
},
json=payload,
timeout=60
)
print(f"Status: {response.status_code}")
result = response.json()
if response.ok:
print(f"✓ Success - Generated {len(result.get('images', []))} image(s)")
for i, img in enumerate(result.get('images', [])):
print(f" Image {i+1}: {img.get('url', 'N/A')[:80]}...")
else:
print(f"✗ Error: {result.get('error', 'Unknown error')}")
except Exception as e:
print(f"✗ Exception: {str(e)}")
if __name__ == '__main__':
print("=== API Testing Suite ===")
print(f"Base URL: {BASE_URL}")
print(f"API Key: {API_KEY[:10]}...")
# Test 1: Simple generation
test_api("Simple text-to-image (1k)", {
'prompt': 'A beautiful sunset',
'size': '1k'
})
# Test 2: High quality
test_api("High quality (4k)", {
'prompt': 'A futuristic city',
'size': '4k'
})
# Test 3: With aspect ratio
test_api("With aspect ratio (16:9)", {
'prompt': 'Wide landscape',
'size': '2k',
'aspectRatio': '16:9'
})
# Test 4: Error handling
test_api("Error handling (missing prompt)", {
'size': '1k'
})
print(f"\n{'='*50}")
print("=== Tests Complete ===")Summary
This testing guide provides comprehensive examples for testing the image generation API locally. Key points:
- Authentication: Always use
Authorization: Bearer <api-key>header - Endpoints: POST to
/api/ai/nano-banana/generate - Quality Levels: 1k/2k (1 credit) or 4k (1.5 credits)
- Image Limits: 3 (Free), 8 (Pro), 14 (Pro Plus)
- File Size: Max 2.5MB per image
- Timeouts: Set appropriate timeout values (60-120 seconds)
For more details, see the API Documentation.
