cURL
Simple Generation
Copy
curl -X POST https://platform.runblob.io/v1/kling/o1-photo/generate \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A futuristic city with flying cars, neon lights, cyberpunk style",
"img_resolution": "2k",
"aspect_ratio": "16:9"
}'
With Reference Images (URLs)
Copy
curl -X POST https://platform.runblob.io/v1/kling/o1-photo/generate \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Combine these images into a beautiful collage with a sunset theme",
"images_url": [
"https://your-storage.com/image1.jpg",
"https://your-storage.com/image2.jpg",
"https://your-storage.com/image3.jpg"
],
"img_resolution": "2k",
"aspect_ratio": "1:1"
}'
With Reference Images (Base64)
Copy
curl -X POST https://platform.runblob.io/v1/kling/o1-photo/generate \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Combine these images into a beautiful collage",
"images_base64": [
"data:image/jpeg;base64,/9j/4AAQSkZJRg...",
"data:image/jpeg;base64,/9j/4AAQSkZJRg..."
],
"img_resolution": "2k",
"aspect_ratio": "1:1"
}'
With Webhook
Copy
curl -X POST https://platform.runblob.io/v1/kling/o1-photo/generate \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Beautiful landscape with mountains and lakes",
"img_resolution": "2k",
"aspect_ratio": "21:9",
"callback_url": "https://your-app.com/webhook/photo"
}'
Check Status
Copy
curl -X GET https://platform.runblob.io/v1/kling/o1-photo/generations/8814c065-88b5-4074-bfcc-32e2d295b2b9 -H "Authorization: Bearer YOUR_API_KEY"
Python
Simple Client
Copy
import requests
import time
class KlingO1PhotoClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://platform.runblob.io"
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def generate(self, prompt, **kwargs):
response = requests.post(
f"{self.base_url}/v1/kling/o1-photo/generate",
headers=self.headers,
json={"prompt": prompt, **kwargs}
)
return response.json()
def generate_with_references(self, prompt, images_url=None, images_base64=None, **kwargs):
payload = {"prompt": prompt, **kwargs}
if images_url:
payload["images_url"] = images_url
if images_base64:
payload["images_base64"] = images_base64
response = requests.post(
f"{self.base_url}/v1/kling/o1-photo/generate",
headers=self.headers,
json=payload
)
return response.json()
def status(self, generation_id):
response = requests.get(
f"{self.base_url}/v1/kling/o1-photo/generations/{generation_id}",
headers=self.headers
)
return response.json()
def wait_for_completion(self, generation_id, poll_interval=10):
while True:
result = self.status(generation_id)
if result["status"] == "completed":
return result["image_url"]
elif result["status"] == "failed":
raise Exception(f"Generation failed: {result.get('message')}")
time.sleep(poll_interval)
# Simple generation
client = KlingO1PhotoClient("YOUR_API_KEY")
result = client.generate(
"A futuristic cyberpunk city",
img_resolution="2k",
aspect_ratio="16:9"
)
image_url = client.wait_for_completion(result["generation_id"])
print(f"Image ready: {image_url}")
# With reference images (URLs)
result = client.generate_with_references(
"Beautiful landscape combining these styles",
images_url=[
"https://example.com/ref1.jpg",
"https://example.com/ref2.jpg"
],
img_resolution="2k",
aspect_ratio="1:1"
)
image_url = client.wait_for_completion(result["generation_id"])
# With reference images (Base64)
result = client.generate_with_references(
"Beautiful landscape combining these styles",
images_base64=[
"data:image/jpeg;base64,/9j/4AAQSkZJRg...",
"data:image/jpeg;base64,/9j/4AAQSkZJRg..."
],
img_resolution="2k",
aspect_ratio="1:1"
)
image_url = client.wait_for_completion(result["generation_id"])
Advanced Usage with Error Handling
Copy
import requests
import time
from typing import Optional, List
class KlingO1PhotoAPI:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://platform.runblob.io/v1/kling/o1-photo"
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def generate(self, prompt: str, img_resolution: str = "2k",
aspect_ratio: str = "1:1",
images_url: Optional[List[str]] = None,
images_base64: Optional[List[str]] = None,
callback_url: Optional[str] = None) -> dict:
"""Create a new image generation."""
payload = {
"prompt": prompt,
"img_resolution": img_resolution,
"aspect_ratio": aspect_ratio
}
total_images = len(images_url or []) + len(images_base64 or [])
if total_images > 5:
raise ValueError("Maximum 5 reference images allowed")
if images_url:
payload["images_url"] = images_url
if images_base64:
payload["images_base64"] = images_base64
if callback_url:
payload["callback_url"] = callback_url
try:
response = requests.post(
f"{self.base_url}/generate",
headers=self.headers,
json=payload
)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 402:
raise Exception("Insufficient credits")
elif e.response.status_code == 401:
raise Exception("Invalid API key")
else:
raise Exception(f"API Error: {e.response.text}")
def get_status(self, generation_id: str) -> dict:
"""Get generation status."""
try:
response = requests.get(
f"{self.base_url}/generations/{generation_id}",
headers=self.headers
)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
raise Exception("Generation not found")
raise Exception(f"API Error: {e.response.text}")
def wait_for_completion(self, generation_id: str,
timeout: int = 600) -> Optional[str]:
"""Wait for generation to complete with timeout."""
start_time = time.time()
while time.time() - start_time < timeout:
result = self.get_status(generation_id)
if result["status"] == "completed":
return result["image_url"]
elif result["status"] == "failed":
error_msg = result.get("message", "Unknown error")
raise Exception(f"Generation failed: {error_msg}")
time.sleep(10)
raise Exception("Generation timeout")
# Usage
try:
client = KlingO1PhotoAPI("YOUR_API_KEY")
# Simple generation
result = client.generate(
prompt="A beautiful sunset over mountains",
img_resolution="2k",
aspect_ratio="16:9"
)
print(f"Generation started: {result['generation_id']}")
print(f"Price: ${result['price']}")
# Wait for completion
image_url = client.wait_for_completion(result['generation_id'])
print(f"Image ready: {image_url}")
# With reference images (URLs)
result = client.generate(
prompt="Combine these styles",
images_url=[
"https://example.com/ref1.jpg",
"https://example.com/ref2.jpg"
],
img_resolution="2k",
callback_url="https://your-app.com/webhook"
)
# With reference images (Base64)
result = client.generate(
prompt="Combine these styles",
images_base64=[
"data:image/jpeg;base64,/9j/4AAQSkZJRg...",
"data:image/jpeg;base64,/9j/4AAQSkZJRg..."
],
img_resolution="2k"
)
except Exception as e:
print(f"Error: {str(e)}")
JavaScript / Node.js
Basic Client
Copy
const fetch = require('node-fetch');
class KlingO1PhotoAPI {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://platform.runblob.io/v1/kling/o1-photo';
}
async generate(params) {
const response = await fetch(`${this.baseUrl}/generate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
img_resolution: '2k',
aspect_ratio: '1:1',
...params
})
});
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
return response.json();
}
async getStatus(generationId) {
const response = await fetch(
`${this.baseUrl}/generations/${generationId}`,
{
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
}
);
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
return response.json();
}
async waitForCompletion(generationId, pollInterval = 10000) {
while (true) {
const result = await this.getStatus(generationId);
if (result.status === 'completed') {
return result.image_url;
} else if (result.status === 'failed') {
throw new Error(`Generation failed: ${result.message}`);
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
}
}
// Usage
const client = new KlingO1PhotoAPI('YOUR_API_KEY');
// Simple generation
client.generate({
prompt: 'A futuristic cyberpunk city'
})
.then(result => {
console.log('Generation ID:', result.generation_id);
return client.waitForCompletion(result.generation_id);
})
.then(imageUrl => {
console.log('Image ready:', imageUrl);
})
.catch(error => {
console.error('Error:', error.message);
});
// With reference images (URLs)
client.generate({
prompt: 'Combine these styles',
images_url: [
'https://example.com/ref1.jpg',
'https://example.com/ref2.jpg'
],
img_resolution: '2k',
aspect_ratio: '16:9'
})
.then(result => client.waitForCompletion(result.generation_id))
.then(imageUrl => console.log('Image ready:', imageUrl));
// With reference images (Base64)
client.generate({
prompt: 'Combine these styles',
images_base64: [
'data:image/jpeg;base64,/9j/4AAQSkZJRg...',
'data:image/jpeg;base64,/9j/4AAQSkZJRg...'
],
img_resolution: '2k'
})
.then(result => client.waitForCompletion(result.generation_id))
.then(imageUrl => console.log('Image ready:', imageUrl));
Async/Await Example
Copy
const generateImage = async () => {
const response = await fetch('https://platform.runblob.io/v1/kling/o1-photo/generate', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: 'A beautiful landscape with mountains',
img_resolution: '2k',
aspect_ratio: '16:9'
})
});
const data = await response.json();
console.log('Generation ID:', data.generation_id);
return data.generation_id;
};
// With reference images (URLs)
const generateWithUrls = async () => {
const response = await fetch('https://platform.runblob.io/v1/kling/o1-photo/generate', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: 'Beautiful collage combining these images',
images_url: [
'https://example.com/ref1.jpg',
'https://example.com/ref2.jpg',
'https://example.com/ref3.jpg'
],
img_resolution: '2k',
aspect_ratio: '1:1',
callback_url: 'https://your-app.com/webhook/photo'
})
});
const data = await response.json();
return data;
};
// With reference images (Base64)
const generateWithBase64 = async () => {
const response = await fetch('https://platform.runblob.io/v1/kling/o1-photo/generate', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: 'Beautiful collage combining these images',
images_base64: [
'data:image/jpeg;base64,/9j/4AAQSkZJRg...',
'data:image/jpeg;base64,/9j/4AAQSkZJRg...'
],
img_resolution: '2k',
aspect_ratio: '1:1'
})
});
const data = await response.json();
return data;
};