Image Generation API Usage Guide
Bring your ideas to life with Radient's Image Generation API. Create breathtaking visuals, unique artwork, and product mockups directly within your applications. Our API provides access to powerful image generation models, offering a blend of simplicity and control for developers.
This guide covers text-to-image and image-to-image generation, along with handling API responses.
Core Concepts
Radient's Image Generation API revolves around the /v1/images/generate
endpoint. You can request images based on text prompts or modify existing images.
Key features:
- Text-to-Image: Generate novel images from descriptive text.
- Image-to-Image: Modify an existing image using a prompt and a source image.
- Synchronous & Asynchronous Modes: Get results immediately for quick generations or poll for status on longer tasks.
- Provider Choice: Select from various underlying image generation models/providers if needed.
Text-to-Image Generation
Create entirely new images from your textual descriptions.
Endpoint: POST /v1/images/generate
Example Request (Python using requests
):
import requests
import json
import time
import os
RADIENT_API_KEY = "YOUR_RADIENT_API_KEY"
RADIENT_BASE_URL = "https://api.radient.com/v1" # Or your specific Radient API endpoint
headers = {
"Authorization": f"Bearer {RADIENT_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"prompt": "A serene bioluminescent forest at night, with glowing mushrooms and mystical creatures, digital painting.",
"num_images": 1,
"image_size": "landscape_16_9", # e.g., "square_hd", "portrait_4_3"
"sync_mode": False # Use False for potentially longer generations to allow polling
# "provider": "your_preferred_provider_id" # Optional
}
def download_image(image_url, filename_prefix="generated_image"):
try:
img_response = requests.get(image_url, stream=True)
img_response.raise_for_status()
# Extract filename from URL or create one
original_filename = image_url.split('/')[-1].split('?')[0] # Basic extraction
if not original_filename:
timestamp = int(time.time())
original_filename = f"{filename_prefix}_{timestamp}.png" # Assume png if unknown
# Ensure a valid extension, default to .png
name, ext = os.path.splitext(original_filename)
if not ext:
ext = ".png"
save_path = f"{name}{ext}"
with open(save_path, 'wb') as f:
for chunk in img_response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Image downloaded successfully: {save_path}")
return save_path
except requests.exceptions.RequestException as e:
print(f"Error downloading image {image_url}: {e}")
return None
try:
response = requests.post(f"{RADIENT_BASE_URL}/images/generate", headers=headers, json=payload)
response.raise_for_status()
generation_data = response.json()
request_id = generation_data.get("request_id")
status = generation_data.get("status")
print(f"Initial request ID: {request_id}, Status: {status}")
if status == "COMPLETED" and generation_data.get("images"):
for img in generation_data["images"]:
print(f"Image URL: {img['url']}")
download_image(img['url'])
elif request_id and status != "FAILED":
print("Polling for results...")
max_wait_time = 120 # seconds
poll_interval = 5 # seconds
start_time = time.time()
while time.time() - start_time < max_wait_time:
time.sleep(poll_interval)
status_payload = {"request_id": request_id}
if payload.get("provider"):
status_payload["provider"] = payload["provider"]
status_response = requests.get(f"{RADIENT_BASE_URL}/images/status", headers=headers, params=status_payload)
status_response.raise_for_status()
status_data = status_response.json()
current_status = status_data.get("status")
print(f"Current status for {request_id}: {current_status}")
if current_status == "COMPLETED":
if status_data.get("images"):
for img in status_data["images"]:
print(f"Image URL: {img['url']}")
download_image(img['url'], f"image_{request_id}")
break
else:
print("Completed but no images found in response.")
break
elif current_status == "FAILED":
print(f"Image generation failed. Error: {status_data.get('error', 'Unknown error')}")
break
else: # Loop finished without break (timeout)
print("Image generation timed out.")
elif status == "FAILED":
print(f"Image generation failed. Error: {generation_data.get('error', 'Unknown error')}")
else:
print("Unexpected initial response:", generation_data)
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print(f"Response body: {response.text}")
except requests.exceptions.RequestException as req_err:
print(f"Request error occurred: {req_err}")
except json.JSONDecodeError:
print("Failed to decode JSON response.")
print(f"Response body: {response.text}")
Key Parameters:
prompt
: Your detailed description of the desired image.image_size
: Controls aspect ratio and general dimensions (e.g.,"square_hd"
,"landscape_16_9"
).num_images
: How many variations to generate.sync_mode
: Iffalse
(recommended for potentially long jobs), you'll receive arequest_id
to poll the/v1/images/status
endpoint.
Response Structure (for sync_mode: false
initial call or /images/status
):
{
"request_id": "imgreq_xxxxxxxxxxxx",
"status": "PROCESSING", // or "COMPLETED", "FAILED"
"images": null, // Populated when status is "COMPLETED"
"provider": "default_provider_id",
"error": null // Populated if status is "FAILED"
}
Response Structure (when status
is COMPLETED
):
{
"request_id": "imgreq_xxxxxxxxxxxx",
"status": "COMPLETED",
"images": [
{
"url": "https://cdn.radient.com/generated_image_xyz.png",
"width": 1024,
"height": 1024,
"content_type": "image/png" // Example
}
],
"provider": "default_provider_id",
"error": null
}
Image-to-Image Generation
Modify an existing image using a text prompt. This is useful for variations, style transfers, or adding elements.
Endpoint: POST /v1/images/generate
Additional Parameters for Image-to-Image:
source_url
(string, required for image-to-image): URL of the base image. This can be a publicly accessible HTTP/HTTPS URL or a base64 encoded Data URI (e.g.,data:image/jpeg;base64,...
).strength
(float, optional): Controls how much the original image is preserved versus how much the prompt influences the result. Values typically range from 0.0 (heavily prompt-influenced) to 1.0 (closer to original). Default may vary by provider.
Example Request (Python using requests
, with local file upload as Data URI):
import requests
import json
import base64
import time
import os # For the download_image function
# (Assume RADIENT_API_KEY, RADIENT_BASE_URL, headers, and download_image function are defined as above)
def image_to_data_uri(file_path):
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
# Determine MIME type (basic implementation)
mime_type = "image/jpeg" # Default
if file_path.lower().endswith(".png"):
mime_type = "image/png"
elif file_path.lower().endswith(".gif"):
mime_type = "image/gif"
# Add more types as needed
return f"data:{mime_type};base64,{encoded_string}"
local_image_path = "path/to/your/source_image.jpg" # Replace with your image path
if not os.path.exists(local_image_path):
print(f"Error: Source image not found at {local_image_path}")
else:
data_uri = image_to_data_uri(local_image_path)
payload_img2img = {
"prompt": "Transform this portrait into a vibrant pop art style.",
"source_url": data_uri,
"strength": 0.7,
"num_images": 1,
"image_size": "square", # Match aspect ratio or let provider adjust
"sync_mode": False
}
try:
response = requests.post(f"{RADIENT_BASE_URL}/images/generate", headers=headers, json=payload_img2img)
response.raise_for_status()
generation_data = response.json()
# (Polling logic similar to text-to-image example would follow here)
request_id = generation_data.get("request_id")
status = generation_data.get("status")
print(f"Image-to-image request ID: {request_id}, Status: {status}")
if status == "COMPLETED" and generation_data.get("images"):
for img in generation_data["images"]:
print(f"Altered Image URL: {img['url']}")
download_image(img['url'], f"altered_{request_id}")
elif request_id and status != "FAILED":
# Implement polling as in the text-to-image example
print("Polling for image-to-image results...")
# ... (polling logic) ...
pass # Placeholder for brevity, refer to text-to-image polling
elif status == "FAILED":
print(f"Image-to-image generation failed. Error: {generation_data.get('error', 'Unknown error')}")
else:
print("Unexpected initial response for image-to-image:", generation_data)
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print(f"Response body: {response.text}")
except requests.exceptions.RequestException as req_err:
print(f"Request error occurred: {req_err}")
except FileNotFoundError: # If image_to_data_uri fails due to path
print(f"Error: Could not find the image at {local_image_path}")
Listing Available Providers
You can query the API to see which image generation providers are available.
Endpoint: GET /v1/images/providers
Example Request (Python using requests
):
import requests
import json
# (Assume RADIENT_API_KEY, RADIENT_BASE_URL, headers are defined)
try:
response = requests.get(f"{RADIENT_BASE_URL}/images/providers", headers=headers)
response.raise_for_status()
providers_data = response.json()
if providers_data.get("providers"):
print("Available Image Generation Providers:")
for provider_id in providers_data["providers"]:
# In a real scenario, provider details might be richer
print(f"- {provider_id}")
else:
print("No providers listed or unexpected response format.")
print("Full response:", providers_data)
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print(f"Response body: {response.text}")
except requests.exceptions.RequestException as req_err:
print(f"Request error occurred: {req_err}")
Expected Response Structure (JSON):
{
"providers": [
"provider_stable_diffusion_xl",
"provider_dalle_3",
"default"
// Example provider IDs
]
}
Best Practices
- Detailed Prompts: The more specific your prompt, the better the results. Include style, subject, mood, and artistic medium.
- Experiment with Parameters: Adjust
strength
(for image-to-image),guidance_scale
, andnum_inference_steps
to fine-tune outputs. - Asynchronous Polling: For applications where users wait, implement robust polling for the
/images/status
endpoint with appropriate timeouts and retry logic. - Error Handling: Check
status
anderror
fields in responses to manage failed generations.
Dive into Radient's Image Generation API and start creating visually compelling content for your projects! For a comprehensive list of all parameters, refer to the main API Reference.