Image Generation in ASI:One
Generate high-quality images from text descriptions using ASI:One's image generation API. This feature allows you to create custom images based on natural language prompts.
Overview
The image generation API accepts text prompts and returns generated images in various sizes. The API supports different image dimensions and uses advanced AI models to create realistic and creative images.
Endpoint: POST https://api.asi1.ai/v1/image/generate
Quick Start
- cURL
- Python
- JavaScript
curl -X POST https://api.asi1.ai/v1/image/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ASI_ONE_API_KEY" \
-d '{
"prompt": "A futuristic city skyline at sunset with flying cars",
"size": "1024x1024",
"model": "asi1-mini"
}'
import os
import requests
import json
import base64
API_KEY = os.getenv("ASI_ONE_API_KEY")
BASE_URL = "https://api.asi1.ai/v1"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"prompt": "A futuristic city skyline at sunset with flying cars",
"size": "1024x1024",
"model": "asi1-mini"
}
response = requests.post(
f"{BASE_URL}/image/generate",
headers=headers,
json=payload
)
# Parse JSON response and save the image
if response.status_code == 200:
result = response.json()
# Extract base64 image from url field
if "images" in result and len(result["images"]) > 0:
image_url = result["images"][0]["url"]
# Check if it's a data URL with base64
if image_url.startswith("data:image/"):
# Extract base64 data (remove data:image/png;base64, prefix)
base64_data = image_url.split(",", 1)[1]
# Decode base64 to binary
image_data = base64.b64decode(base64_data)
# Save to file
with open("generated_image.png", "wb") as f:
f.write(image_data)
print("Image saved as 'generated_image.png'")
else:
print(f"Unexpected URL format: {image_url[:100]}...")
else:
print("No images found in response")
else:
print(f"Error: {response.status_code}")
print(response.text)
import fetch from "node-fetch";
import fs from "fs";
const API_KEY = process.env.ASI_ONE_API_KEY;
const BASE_URL = "https://api.asi1.ai/v1";
const payload = {
prompt: "A futuristic city skyline at sunset with flying cars",
size: "1024x1024",
model: "asi1-mini"
};
const response = await fetch(`${BASE_URL}/image/generate`, {
method: "POST",
headers: {
"Authorization": `Bearer ${API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
// Parse JSON response and save the image
if (response.ok) {
const result = await response.json();
// Extract base64 image from url field
if (result.images && result.images.length > 0) {
const imageUrl = result.images[0].url;
// Check if it's a data URL with base64
if (imageUrl.startsWith("data:image/")) {
// Extract base64 data (remove data:image/png;base64, prefix)
const base64Data = imageUrl.split(",")[1];
// Decode base64 to binary
const imageData = Buffer.from(base64Data, 'base64');
// Save to file
fs.writeFileSync("generated_image.png", imageData);
console.log("Image saved as 'generated_image.png'");
} else {
console.log(`Unexpected URL format: ${imageUrl.substring(0, 100)}...`);
}
} else {
console.log("No images found in response");
}
} else {
console.error(`Error: ${response.status}`);
console.error(await response.text());
}
API Reference
Request Parameters
Parameter | Type | Required | Description | Default |
---|---|---|---|---|
prompt | string | Yes | Text description of the image to generate | - |
size | string | No | Image dimensions | "1024x1024" |
model | string | No | Image generation model to use | "asi1-mini" |
Supported Image Sizes
Size | Description | Use Case |
---|---|---|
1024x1024 | Square image | General purpose, avatars, icons |
1792x1024 | Landscape image | Wallpapers, banners, wide scenes |
1024x1792 | Portrait image | Mobile wallpapers, tall scenes |
Response Format
The API returns a JSON response containing the generated image as a base64-encoded data URL.
Success Response:
- Status Code: 200 OK
- Content-Type: application/json
- Body: JSON object with image data
{
"status": 1,
"message": "Success",
"created": 1753792957496,
"images": [
{
"url": "data:image/png;base64,iVBORw0KGgoAAA... (truncated)"
}
]
}
Examples
Basic Image Generation
- cURL
- Python
- JavaScript
curl -X POST https://api.asi1.ai/v1/image/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ASI_ONE_API_KEY" \
-d '{
"prompt": "A serene mountain landscape with snow-capped peaks and a crystal clear lake"
}'
import os
import requests
import json
import base64
def generate_image(prompt, size="1024x1024", model="asi1-mini", filename="generated_image.png"):
API_KEY = os.getenv("ASI_ONE_API_KEY")
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"prompt": prompt,
"size": size,
"model": model
}
response = requests.post(
"https://api.asi1.ai/v1/image/generate",
headers=headers,
json=payload
)
if response.status_code == 200:
result = response.json()
# Extract base64 image from url field
if "images" in result and len(result["images"]) > 0:
image_url = result["images"][0]["url"]
# Check if it's a data URL with base64
if image_url.startswith("data:image/"):
# Extract base64 data (remove data:image/png;base64, prefix)
base64_data = image_url.split(",", 1)[1]
# Decode base64 to binary
image_data = base64.b64decode(base64_data)
# Save to file
with open(filename, "wb") as f:
f.write(image_data)
print(f"Image saved as '{filename}'")
return {"success": True, "filename": filename}
else:
print(f"Unexpected URL format: {image_url[:100]}...")
return {"success": False, "error": "Unexpected URL format"}
else:
print("No images found in response")
return {"success": False, "error": "No images found in response"}
else:
print(f"Error: {response.status_code}")
print(response.text)
return {"success": False, "error": response.text}
# Generate a mountain landscape
result = generate_image("A serene mountain landscape with snow-capped peaks and a crystal clear lake")
print(result)
import fetch from "node-fetch";
import fs from "fs";
async function generateImage(prompt, size = "1024x1024", model = "asi1-mini", filename = "generated_image.png") {
const API_KEY = process.env.ASI_ONE_API_KEY;
const response = await fetch("https://api.asi1.ai/v1/image/generate", {
method: "POST",
headers: {
"Authorization": `Bearer ${API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
prompt: prompt,
size: size,
model: model
})
});
if (response.ok) {
const result = await response.json();
// Extract base64 image from url field
if (result.images && result.images.length > 0) {
const imageUrl = result.images[0].url;
// Check if it's a data URL with base64
if (imageUrl.startsWith("data:image/")) {
// Extract base64 data (remove data:image/png;base64, prefix)
const base64Data = imageUrl.split(",")[1];
// Decode base64 to binary
const imageData = Buffer.from(base64Data, 'base64');
// Save to file
fs.writeFileSync(filename, imageData);
console.log(`Image saved as '${filename}'`);
return { success: true, filename };
} else {
console.log(`Unexpected URL format: ${imageUrl.substring(0, 100)}...`);
return { success: false, error: "Unexpected URL format" };
}
} else {
console.log("No images found in response");
return { success: false, error: "No images found in response" };
}
} else {
const error = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${error}`);
}
}
// Generate a mountain landscape
const result = await generateImage("A serene mountain landscape with snow-capped peaks and a crystal clear lake");
console.log(result);
Landscape Image Generation
- cURL
- Python
- JavaScript
curl -X POST https://api.asi1.ai/v1/image/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ASI_ONE_API_KEY" \
-d '{
"prompt": "A beautiful sunset over the ocean with palm trees silhouetted against the sky",
"size": "1792x1024"
}'
# Generate a landscape sunset image
result = generate_image(
"A beautiful sunset over the ocean with palm trees silhouetted against the sky",
size="1792x1024"
)
print(result)
// Generate a landscape sunset image
const result = await generateImage(
"A beautiful sunset over the ocean with palm trees silhouetted against the sky",
"1792x1024"
);
console.log(result);
Portrait Image Generation
- cURL
- Python
- JavaScript
curl -X POST https://api.asi1.ai/v1/image/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ASI_ONE_API_KEY" \
-d '{
"prompt": "A majestic waterfall cascading down a cliff face with mist and rainbows",
"size": "1024x1792"
}'
# Generate a portrait waterfall image
result = generate_image(
"A majestic waterfall cascading down a cliff face with mist and rainbows",
size="1024x1792"
)
print(result)
// Generate a portrait waterfall image
const result = await generateImage(
"A majestic waterfall cascading down a cliff face with mist and rainbows",
"1024x1792"
);
console.log(result);
Error Handling
Common Error Responses
Status Code | Error Type | Description |
---|---|---|
400 | Bad Request | Invalid parameters or malformed request |
401 | Unauthorized | Invalid or missing API key |
404 | Not Found | Endpoint not found |
500 | Internal Server Error | Server-side error |
Example Error Response
{
"error": {
"message": "Invalid prompt provided",
"type": "invalid_request_error",
"code": 400
}
}
Best Practices
Writing Effective Prompts
- Be Specific: Include details about style, mood, lighting, and composition
- Use Descriptive Language: Mention colors, textures, and artistic styles
- Specify Perspective: Include camera angles and viewpoints
- Add Context: Provide background information and setting details
Example Prompts
Category | Good Prompt | Poor Prompt |
---|---|---|
Landscape | "A misty mountain valley at dawn with golden sunlight filtering through pine trees" | "mountains" |
Portrait | "A professional headshot of a confident businesswoman in a modern office setting" | "person" |
Abstract | "A vibrant abstract painting with swirling colors in the style of Van Gogh" | "abstract art" |
Rate Limiting
- The API applies rate limits based on your plan
- Monitor your usage to avoid hitting limits
- Implement exponential backoff for retries
Image Quality Tips
- Use High-Resolution Sizes: Choose larger sizes for better quality
- Provide Detailed Prompts: More specific prompts yield better results
- Experiment with Different Models: Try different models for various styles
- Consider Aspect Ratios: Choose appropriate sizes for your use case
Integration Examples
Web Application Integration
// Frontend image generation with loading states
async function generateImageWithUI(prompt) {
const loadingElement = document.getElementById('loading');
const resultElement = document.getElementById('result');
try {
loadingElement.textContent = 'Generating image...';
const response = await fetch('/api/generate-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt })
});
const result = await response.json();
if (result.images && result.images[0]) {
const img = document.createElement('img');
img.src = result.images[0].url;
img.alt = prompt;
resultElement.appendChild(img);
}
} catch (error) {
console.error('Error generating image:', error);
} finally {
loadingElement.textContent = '';
}
}
Batch Image Generation
import asyncio
import aiohttp
async def generate_multiple_images(prompts):
API_KEY = os.getenv("ASI_ONE_API_KEY")
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
async with aiohttp.ClientSession() as session:
tasks = []
for prompt in prompts:
payload = {"prompt": prompt, "size": "1024x1024"}
task = session.post(
"https://api.asi1.ai/v1/image/generate",
headers=headers,
json=payload
)
tasks.append(task)
responses = await asyncio.gather(*tasks)
return [await resp.json() for resp in responses]
# Generate multiple images concurrently
prompts = [
"A cyberpunk city street at night",
"A peaceful forest clearing with sunlight",
"A futuristic spaceship in orbit"
]
results = await generate_multiple_images(prompts)
for i, result in enumerate(results):
print(f"Image {i+1}: {result['images'][0]['url']}")