Flux Krea's API opens powerful AI image generation capabilities to developers worldwide. This comprehensive guide covers everything from initial setup to advanced integration patterns, providing the knowledge needed to build production-ready applications with Flux Krea's cutting-edge image generation technology.
Getting Started with Flux Krea API
The Flux Krea API provides RESTful endpoints for generating high-quality, photorealistic images from text descriptions. Built on the open-source Flux model, the API offers both cloud-hosted and self-hosted deployment options, giving developers flexibility in implementation.
API Overview and Capabilities
Key features of the Flux Krea API include:
- Text-to-image generation: Create images from detailed text prompts
- High-speed processing: Generate images in 1-2 seconds
- Photorealistic quality: Professional-grade image output
- Flexible parameters: Control over resolution, quality, and generation settings
- Batch processing: Generate multiple images efficiently
- Webhook support: Asynchronous processing notifications
Authentication and API Keys
Flux Krea uses API key authentication for secure access. Here's how to get started:
1. Obtain API Key
# Register at https://flux-krea.pro/developers
# Navigate to API Dashboard
# Generate new API key
# Copy and securely store your key
2. Basic Authentication Header
Authorization: Bearer your_api_key_here
Core API Endpoints
Text-to-Image Generation
The primary endpoint for generating images from text prompts:
Endpoint
POST https://api.flux-krea.pro/v1/generate
Request Parameters
{
"prompt": "string (required)",
"width": "integer (optional, default: 1024)",
"height": "integer (optional, default: 1024)",
"guidance_scale": "float (optional, default: 7.5)",
"num_inference_steps": "integer (optional, default: 4)",
"seed": "integer (optional)",
"num_images": "integer (optional, default: 1, max: 4)"
}
Parameter Descriptions
| Parameter | Type | Description | Range |
|---|---|---|---|
| prompt | string | Text description of desired image | 1-1000 characters |
| width | integer | Image width in pixels | 512-2048 |
| height | integer | Image height in pixels | 512-2048 |
| guidance_scale | float | Prompt adherence strength | 1.0-20.0 |
| num_inference_steps | integer | Generation quality vs speed | 1-50 |
| seed | integer | Random seed for reproducibility | 0-2147483647 |
Response Format
Successful Response
{
"status": "success",
"request_id": "uuid-string",
"images": [
{
"url": "https://cdn.flux-krea.pro/images/generated/image_id.jpg",
"seed": 1234567890,
"width": 1024,
"height": 1024
}
],
"generation_time": 1.23,
"credits_used": 1
}
Implementation Examples
Python Integration
Basic Python Example
import requests
import json
from typing import Optional, Dict, Any
class FluxKreaClient:
def __init__(self, api_key: str, base_url: str = "https://api.flux-krea.pro/v1"):
self.api_key = api_key
self.base_url = base_url
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def generate_image(self,
prompt: str,
width: int = 1024,
height: int = 1024,
guidance_scale: float = 7.5,
num_inference_steps: int = 4,
seed: Optional[int] = None) -> Dict[Any, Any]:
"""
Generate an image from a text prompt.
Args:
prompt: Text description of the desired image
width: Image width in pixels
height: Image height in pixels
guidance_scale: Prompt adherence strength (1.0-20.0)
num_inference_steps: Quality vs speed trade-off (1-50)
seed: Random seed for reproducibility
Returns:
Dictionary containing generation results
"""
payload = {
"prompt": prompt,
"width": width,
"height": height,
"guidance_scale": guidance_scale,
"num_inference_steps": num_inference_steps
}
if seed is not None:
payload["seed"] = seed
try:
response = requests.post(
f"{self.base_url}/generate",
headers=self.headers,
json=payload,
timeout=30
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
raise Exception(f"API request failed: {e}")
# Usage example
client = FluxKreaClient(api_key="your_api_key_here")
result = client.generate_image(
prompt="Professional headshot of a confident businesswoman in modern office",
width=1024,
height=1024,
guidance_scale=7.5,
num_inference_steps=4
)
print(f"Generated image URL: {result['images'][0]['url']}")
print(f"Generation time: {result['generation_time']:.2f} seconds")
JavaScript/Node.js Integration
Node.js Example
const axios = require('axios');
class FluxKreaClient {
constructor(apiKey, baseUrl = 'https://api.flux-krea.pro/v1') {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
};
}
async generateImage({
prompt,
width = 1024,
height = 1024,
guidance_scale = 7.5,
num_inference_steps = 4,
seed = null
}) {
const payload = {
prompt,
width,
height,
guidance_scale,
num_inference_steps
};
if (seed !== null) {
payload.seed = seed;
}
try {
const response = await axios.post(
`${this.baseUrl}/generate`,
payload,
{
headers: this.headers,
timeout: 30000
}
);
return response.data;
} catch (error) {
if (error.response) {
throw new Error(`API Error: ${error.response.status} - ${error.response.data.message}`);
} else {
throw new Error(`Request failed: ${error.message}`);
}
}
}
}
// Usage example
const client = new FluxKreaClient('your_api_key_here');
async function generateExample() {
try {
const result = await client.generateImage({
prompt: 'Serene mountain landscape at sunrise with misty valleys',
width: 1024,
height: 1024,
guidance_scale: 7.5,
num_inference_steps: 4
});
console.log('Generated image URL:', result.images[0].url);
console.log('Generation time:', result.generation_time, 'seconds');
} catch (error) {
console.error('Generation failed:', error.message);
}
}
generateExample();
cURL Examples
Basic cURL Request
curl -X POST https://api.flux-krea.pro/v1/generate \
-H "Authorization: Bearer your_api_key_here" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Professional product photography of modern smartphone on white background",
"width": 1024,
"height": 1024,
"guidance_scale": 7.5,
"num_inference_steps": 4
}'
Advanced Features and Patterns
Batch Processing
Generate multiple images efficiently with batch requests:
Batch Generation Example
def batch_generate(client, prompts, **kwargs):
"""
Generate multiple images from a list of prompts.
Args:
client: FluxKreaClient instance
prompts: List of text prompts
**kwargs: Additional generation parameters
Returns:
List of generation results
"""
results = []
for prompt in prompts:
try:
result = client.generate_image(prompt=prompt, **kwargs)
results.append({
'prompt': prompt,
'success': True,
'data': result
})
except Exception as e:
results.append({
'prompt': prompt,
'success': False,
'error': str(e)
})
return results
# Usage
prompts = [
"Modern minimalist living room with natural lighting",
"Cozy coffee shop interior with warm atmosphere",
"Professional office space with ergonomic furniture"
]
batch_results = batch_generate(client, prompts, width=1024, height=1024)
Asynchronous Processing
For high-volume applications, use asynchronous processing with webhooks:
Async Generation Request
POST https://api.flux-krea.pro/v1/generate/async
{
"prompt": "Your image description",
"webhook_url": "https://your-domain.com/webhook/flux-krea",
"callback_data": {
"user_id": "12345",
"project_id": "project_abc"
},
// ... other parameters
}
Webhook Handler Example
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhook/flux-krea', methods=['POST'])
def handle_flux_webhook():
"""
Handle webhook notifications from Flux Krea API
"""
try:
data = request.get_json()
# Verify webhook signature (recommended for production)
# verify_webhook_signature(request.headers, data)
request_id = data.get('request_id')
status = data.get('status')
if status == 'completed':
images = data.get('images', [])
callback_data = data.get('callback_data', {})
# Process completed generation
process_completed_generation(request_id, images, callback_data)
elif status == 'failed':
error_message = data.get('error', 'Unknown error')
# Handle failed generation
handle_generation_failure(request_id, error_message)
return jsonify({'status': 'received'}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
def process_completed_generation(request_id, images, callback_data):
"""Process successfully generated images"""
user_id = callback_data.get('user_id')
project_id = callback_data.get('project_id')
# Save images to database
# Notify user
# Update project status
pass
def handle_generation_failure(request_id, error_message):
"""Handle failed generation attempts"""
# Log error
# Notify user
# Implement retry logic if appropriate
pass
Error Handling and Best Practices
Common Error Responses
| Status Code | Error Type | Description | Action |
|---|---|---|---|
| 400 | Bad Request | Invalid parameters or malformed request | Check request format and parameters |
| 401 | Unauthorized | Invalid or missing API key | Verify API key and authorization header |
| 403 | Forbidden | Insufficient permissions or quota exceeded | Check account status and limits |
| 429 | Rate Limited | Too many requests | Implement rate limiting and retry logic |
| 500 | Server Error | Internal server error | Retry with exponential backoff |
Robust Error Handling Implementation
Production-Ready Error Handling
import time
import random
from typing import Optional
class FluxKreaError(Exception):
"""Base exception for Flux Krea API errors"""
pass
class RateLimitError(FluxKreaError):
"""Raised when rate limit is exceeded"""
pass
class QuotaExceededError(FluxKreaError):
"""Raised when quota is exceeded"""
pass
class FluxKreaClient:
def __init__(self, api_key: str, max_retries: int = 3):
self.api_key = api_key
self.max_retries = max_retries
# ... other initialization
def generate_image_with_retry(self, **kwargs) -> Dict[Any, Any]:
"""
Generate image with automatic retry logic
"""
last_exception = None
for attempt in range(self.max_retries + 1):
try:
return self.generate_image(**kwargs)
except requests.exceptions.HTTPError as e:
last_exception = e
if e.response.status_code == 429:
# Rate limited - wait and retry
wait_time = self._calculate_backoff(attempt)
time.sleep(wait_time)
continue
elif e.response.status_code == 403:
error_data = e.response.json()
if 'quota_exceeded' in error_data.get('error_code', ''):
raise QuotaExceededError("API quota exceeded")
else:
raise FluxKreaError(f"Forbidden: {error_data.get('message')}")
elif e.response.status_code >= 500:
# Server error - retry with backoff
if attempt < self.max_retries:
wait_time = self._calculate_backoff(attempt)
time.sleep(wait_time)
continue
else:
raise FluxKreaError(f"Server error after {self.max_retries} retries")
else:
# Client error - don't retry
raise FluxKreaError(f"Client error: {e.response.status_code}")
except requests.exceptions.RequestException as e:
last_exception = e
if attempt < self.max_retries:
wait_time = self._calculate_backoff(attempt)
time.sleep(wait_time)
continue
raise FluxKreaError(f"Failed after {self.max_retries} retries: {last_exception}")
def _calculate_backoff(self, attempt: int) -> float:
"""
Calculate exponential backoff with jitter
"""
base_delay = 2 ** attempt
jitter = random.uniform(0.1, 0.5)
return min(base_delay + jitter, 60) # Cap at 60 seconds
Rate Limiting and Optimization
Rate Limiting Implementation
import threading
from collections import deque
from time import time
class RateLimiter:
def __init__(self, max_requests: int, time_window: int):
self.max_requests = max_requests
self.time_window = time_window
self.requests = deque()
self.lock = threading.Lock()
def acquire(self) -> bool:
"""
Attempt to acquire permission for a request
Returns True if request is allowed, False otherwise
"""
with self.lock:
now = time()
# Remove old requests outside time window
while self.requests and self.requests[0] <= now - self.time_window:
self.requests.popleft()
# Check if we can make another request
if len(self.requests) < self.max_requests:
self.requests.append(now)
return True
return False
def wait_time(self) -> float:
"""
Calculate how long to wait before next request is allowed
"""
with self.lock:
if len(self.requests) < self.max_requests:
return 0
oldest_request = self.requests[0]
return max(0, self.time_window - (time() - oldest_request))
class RateLimitedFluxClient(FluxKreaClient):
def __init__(self, api_key: str, requests_per_minute: int = 60):
super().__init__(api_key)
self.rate_limiter = RateLimiter(requests_per_minute, 60)
def generate_image(self, **kwargs):
"""
Generate image with automatic rate limiting
"""
if not self.rate_limiter.acquire():
wait_time = self.rate_limiter.wait_time()
time.sleep(wait_time)
return super().generate_image(**kwargs)
Testing and Development
Unit Testing
Unit Test Example
import unittest
from unittest.mock import patch, Mock
from your_module import FluxKreaClient
class TestFluxKreaClient(unittest.TestCase):
def setUp(self):
self.client = FluxKreaClient(api_key="test_key")
@patch('requests.post')
def test_successful_generation(self, mock_post):
# Mock successful response
mock_response = Mock()
mock_response.json.return_value = {
"status": "success",
"request_id": "test-uuid",
"images": [{
"url": "https://example.com/image.jpg",
"seed": 12345,
"width": 1024,
"height": 1024
}],
"generation_time": 1.5,
"credits_used": 1
}
mock_response.raise_for_status.return_value = None
mock_post.return_value = mock_response
# Test generation
result = self.client.generate_image(
prompt="test prompt",
width=1024,
height=1024
)
# Assertions
self.assertEqual(result["status"], "success")
self.assertEqual(len(result["images"]), 1)
self.assertIn("url", result["images"][0])
@patch('requests.post')
def test_error_handling(self, mock_post):
# Mock error response
mock_response = Mock()
mock_response.raise_for_status.side_effect = requests.exceptions.HTTPError("400 Client Error")
mock_post.return_value = mock_response
# Test error handling
with self.assertRaises(Exception):
self.client.generate_image(prompt="test prompt")
if __name__ == '__main__':
unittest.main()
Local Development Setup
For local development and testing, Flux Krea provides a development environment:
Development Environment Setup
# Install Flux Krea development SDK
pip install flux-krea-dev
# Set up local development server
flux-krea serve --dev --port 8080
# Configure client for local development
client = FluxKreaClient(
api_key="dev_key",
base_url="http://localhost:8080/v1"
)
# Test with development server
result = client.generate_image(
prompt="Development test image",
width=512,
height=512
)
Security Best Practices
API Key Management
- Environment Variables: Store API keys in environment variables, never in code
- Key Rotation: Regularly rotate API keys for enhanced security
- Scope Limitation: Use API keys with minimal required permissions
- Monitoring: Monitor API key usage for unusual activity
Secure Configuration
# .env file
FLUX_KREA_API_KEY=your_secure_api_key_here
FLUX_KREA_BASE_URL=https://api.flux-krea.pro/v1
# Python configuration
import os
from dotenv import load_dotenv
load_dotenv()
client = FluxKreaClient(
api_key=os.getenv('FLUX_KREA_API_KEY'),
base_url=os.getenv('FLUX_KREA_BASE_URL')
)
Request Validation
Input Validation Example
def validate_generation_params(prompt, width, height, guidance_scale):
"""
Validate parameters before sending to API
"""
if not isinstance(prompt, str) or len(prompt) == 0:
raise ValueError("Prompt must be a non-empty string")
if len(prompt) > 1000:
raise ValueError("Prompt must be less than 1000 characters")
if not (512 <= width <= 2048) or not (512 <= height <= 2048):
raise ValueError("Width and height must be between 512 and 2048")
if not (1.0 <= guidance_scale <= 20.0):
raise ValueError("Guidance scale must be between 1.0 and 20.0")
# Check for potentially harmful content
if contains_harmful_content(prompt):
raise ValueError("Prompt contains inappropriate content")
def contains_harmful_content(prompt):
"""
Basic content filtering (implement more sophisticated filtering as needed)
"""
harmful_keywords = ['violence', 'inappropriate', 'harmful']
return any(keyword in prompt.lower() for keyword in harmful_keywords)
Performance Optimization
Caching Strategies
Result Caching Implementation
import hashlib
import json
from typing import Optional
class CachedFluxClient(FluxKreaClient):
def __init__(self, api_key: str, cache_backend=None):
super().__init__(api_key)
self.cache = cache_backend or {}
def generate_image_cached(self, **kwargs) -> Dict[Any, Any]:
"""
Generate image with caching support
"""
# Create cache key from parameters
cache_key = self._create_cache_key(kwargs)
# Check cache first
if cache_key in self.cache:
return self.cache[cache_key]
# Generate image if not cached
result = self.generate_image(**kwargs)
# Cache the result
self.cache[cache_key] = result
return result
def _create_cache_key(self, params: Dict[Any, Any]) -> str:
"""
Create a unique cache key from parameters
"""
# Sort parameters for consistent keys
sorted_params = json.dumps(params, sort_keys=True)
return hashlib.md5(sorted_params.encode()).hexdigest()
Connection Pooling
HTTP Session Management
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
class OptimizedFluxClient(FluxKreaClient):
def __init__(self, api_key: str):
super().__init__(api_key)
# Configure session with connection pooling and retries
self.session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
)
adapter = HTTPAdapter(
max_retries=retry_strategy,
pool_connections=10,
pool_maxsize=20
)
self.session.mount("http://", adapter)
self.session.mount("https://", adapter)
self.session.headers.update(self.headers)
def generate_image(self, **kwargs):
"""
Generate image using optimized session
"""
payload = self._build_payload(**kwargs)
response = self.session.post(
f"{self.base_url}/generate",
json=payload,
timeout=30
)
response.raise_for_status()
return response.json()
Conclusion
The Flux Krea API provides powerful capabilities for integrating AI image generation into your applications. By following the patterns and best practices outlined in this guide, you can build robust, efficient, and scalable solutions that leverage Flux Krea's cutting-edge technology.
Remember to implement proper error handling, rate limiting, and security measures in your production applications. Start with simple implementations and gradually add sophisticated features like caching, batch processing, and asynchronous workflows as your needs evolve.
For additional support and advanced use cases, consult the official Flux Krea API documentation and join the developer community for updates and best practices sharing.