OpenAI-Compatible
Image Generation API

Comprehensive API for image generation, segmentation, upscaling, background removal, and media retrieval. OpenAI-compatible with powerful additional features.

Lightning Fast
AI Segmentation
Image Upscaling
Quick Start
curl -X POST "https://api.univence.com/v1/images/generations" \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key-here" \
-d '{
"model": "z-image-turbo",
"prompt": "a beautiful sunset"
}'

Overview

Everything you need to know about the API

Base URL

https://api.univence.com

Authentication

All endpoints require authentication via:

  • API Key: Include X-API-Key: your-api-key in headers
  • User Session: Or authenticate with your user account

Getting Started

1. Sign up at univence.com

2. Visit univence.com/account to generate your API key

3. Start making requests!

API Endpoints

Complete documentation for all endpoints

POST
/v1/images/generations

1. Generate Single Image

Generate a single image from a text prompt using advanced AI models. Supports various image sizes and generation parameters.

Request Parameters

Parameter Type Required Description Example
model string Yes The AI model to use for generation "z-image-turbo"
prompt string Yes Text description of the image to generate "a beautiful sunset over mountains"
image_size string No Output image dimensions "1024x1024"
negative_prompt string No Things to avoid in the image "blurry, low quality"
seed integer No Random seed for reproducible results 12345
num_inference_steps integer No Number of denoising steps (1-100) 50
guidance_scale float No How closely to follow the prompt (1-20) 7.5

Response

{
  "created": 1634567890,
  "data": [
    {
 "url": "https://api.univence.com/v1/media/abc123.jpg",
 "revised_prompt": "a beautiful sunset over mountains"
    }
  ]
}
POST
/v1/images/generations/batch

2. Generate Batch Images

Generate up to 5 images simultaneously in a single request for maximum efficiency.

Request Parameters

Parameter Type Required Description Example
requests array Yes Array of generation requests (max 5) [{...}, {...}]
response_format string No Response format: "url" or "b64_json" "url"

Example Request

curl -X POST "https://api.univence.com/v1/images/generations/batch" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{
    "requests": [
 {
 "model": "z-image-turbo",
 "prompt": "a red sports car"
 },
 {
 "model": "z-image-turbo", 
 "prompt": "a blue sports car"
 }
    ]
  }'
GET
/v1/media/{mediaFileId}

3. Get Media File by ID

Retrieve comprehensive file access and management for all generated content.

Path Parameters

Parameter Type Required Description Example
mediaFileId string Yes Unique identifier for the media file "abc123def456"

Query Parameters

Parameter Type Required Description Example
format string No Output format: "original", "jpg", "png", "webp" "jpg"
quality integer No Compression quality (1-100) 90

Response Format

{
  "id": "abc123def456",
  "url": "https://api.univence.com/v1/media/abc123def456.jpg",
  "created_at": "2025-01-23T10:30:00Z",
  "expires_at": "2025-01-30T10:30:00Z",
  "content_type": "image/jpeg",
  "size_bytes": 2048576,
  "width": 1024,
  "height": 1024,
  "metadata": {
    "model": "z-image-turbo",
    "prompt": "a beautiful sunset"
  }
}
POST
/v1/images/segmentations

4. Image Segmentation

AI-powered object segmentation and mask generation for precise image editing.

Request Parameters

Parameter Type Required Description Example
image_url string Yes URL of the image to segment "https://example.com/image.jpg"
model string No Segmentation model type "sam-vit-h"
confidence_threshold float No Minimum confidence for segmentation (0-1) 0.7
output_format string No Mask output format: "png" or "json" "png"
POST
/v1/images/upscale

5. Image Upscaling

Enhance and upscale existing images using advanced AI algorithms. Supports multiple upscaling methods and factors (2x, 4x, 8x).

Available Models

Model Description Best For Supported Factors
realesrgan_2x Real-ESRGAN 2x upscaling General photos, landscapes 2x
realesrgan_4x Real-ESRGAN 4x upscaling High-quality photos, portraits 4x
realesrgan_4x_anime Real-ESRGAN optimized for anime Anime, cartoon, illustrations 4x
swin2sr Swin2SR transformer-based High-detail restoration 2x, 4x
lanczos Classical Lanczos interpolation Simple upscaling, fast processing 2x, 4x, 8x

Request Parameters

Parameter Type Required Description Example
image_url string Yes URL of the image to upscale "https://example.com/image.jpg"
upscale_factor integer Yes Upscaling factor: 2, 4, or 8 4
model string No Upscaling model (defaults to realesrgan_4x) "realesrgan_4x"
enhance_details boolean No Enhance fine details during upscaling true
noise_reduction boolean No Apply noise reduction before upscaling false
output_format string No Output format: "png", "jpg", "webp" "png"

Response Format

{
  "created": 1634567890,
  "data": [
    {
 "url": "https://api.univence.com/v1/media/upscale_abc123.jpg",
 "original_size": "512x512",
 "upscale_factor": 4,
 "new_size": "2048x2048",
 "model_used": "realesrgan_4x",
 "processing_time": 2.34,
 "file_size": "2.1MB"
    }
  ]
}
POST
/v1/images/remove-background

6. Background Removal (Image)

Remove backgrounds from images with AI-powered segmentation. Returns transparent PNG images.

Request Parameters

Parameter Type Required Description Example
image_url string Yes URL of the image to process "https://example.com/photo.jpg"
return_mask boolean No Return segmentation mask instead of processed image false
edge_smooth integer No Edge smoothing radius (0-20) 5
output_format string No Output format: "png" or "json" "png"

Response Format

{
  "created": 1634567890,
  "data": [
    {
 "url": "https://api.univence.com/v1/media/nobg_abc123.png",
 "original_url": "https://example.com/photo.jpg",
 "confidence": 0.98,
 "processing_time": 1.2,
 "foreground_detected": true,
 "file_size": 1048576
    }
  ]
}

Example Request

curl -X POST "https://api.univence.com/v1/images/remove-background" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{
    "image_url": "https://example.com/person.jpg",
    "edge_smooth": 5,
    "output_format": "png"
  }'
POST
/v1/videos/remove-background

7. Background Removal (Video)

Remove backgrounds from videos with per-frame processing. Supports object tracking and background replacement.

Request Parameters

Parameter Type Required Description Example
video_url string Yes URL of the video to process "https://example.com/video.mp4"
background_type string No "transparent", "color", or "image" "transparent"
background_value string No Hex color (if type=color) or image URL (if type=image) "#00FF00"
frame_interval integer No Process every N frames (1-10) 3
max_duration integer No Maximum video duration in seconds 300

Response Format

{
  "created": 1634567890,
  "data": {
    "video_url": "https://api.univence.com/v1/media/nobg_video_abc123.mp4",
    "original_url": "https://example.com/video.mp4",
    "frames_processed": 300,
    "processing_time": 45.6,
    "resolution": "1920x1080",
    "file_size": 52428800,
    "format": "mp4"
  }
}

Example Request

curl -X POST "https://api.univence.com/v1/videos/remove-background" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{
    "video_url": "https://example.com/video.mp4",
    "background_type": "color",
    "background_value": "#00FF00",
    "frame_interval": 3
  }'

Error Handling

Understanding and handling API errors effectively

HTTP Status Codes

Status Code Description Common Causes
200 Success Request completed successfully
201 Created Resource created successfully (batch operations)
400 Bad Request Invalid parameters, malformed JSON
401 Unauthorized Missing or invalid API key
402 Payment Required Insufficient credits or billing issues
404 Not Found Media file not found or expired
413 Payload Too Large Image/video file too large
429 Rate Limited Too many requests, quota exceeded
500 Server Error Internal server error, try again later
503 Service Unavailable Model temporarily unavailable

Error Response Format

{
  "error": {
    "code": "INVALID_MODEL",
    "message": "The specified model 'invalid-model' is not available",
    "type": "invalid_request_error",
    "details": {
 "available_models": ["z-image-turbo", "longcat-image-edit"],
 "request_id": "req_123456789",
 "timestamp": "2025-12-20T18:20:05Z"
    }
  }
}

Common Error Codes

Error Code Description Solution
INVALID_API_KEY API key is missing or invalid Check your API key and ensure it's properly formatted
INSUFFICIENT_CREDITS Not enough credits for the request Add credits to your account or upgrade your plan
RATE_LIMIT_EXCEEDED Too many requests in a short time Implement rate limiting or upgrade your plan
INVALID_IMAGE_URL Image URL is inaccessible or invalid Verify the image URL is publicly accessible
PROMPT_TOO_LONG Prompt exceeds maximum length Shorten your prompt or use our prompt optimization
INVALID_UPSCALE_FACTOR Upscale factor must be 2, 4, or 8 Use only supported upscale factors
VIDEO_TOO_LONG Video exceeds maximum duration Shorten video or increase max_duration parameter
BATCH_SIZE_EXCEEDED Batch request exceeds 5 images Limit batch requests to 5 images maximum

Credit System & Pricing

Understanding costs and credit usage

Credit Value

1 Credit = $0.01 USD

Credits are the universal currency for all API operations. Purchase credits in bulk for discounts.

Image Generation

$0.002 /image

0.2 credits per generation

  • All image sizes supported
  • Advanced parameters included
  • High-quality output

Image Segmentation

$0.0025 /image

0.25 credits per image

  • AI-powered object detection
  • Precise mask generation
  • Multiple output formats

Video Segmentation

$0.0025 /frame

0.25 credits per frame

  • Per-frame processing
  • Object tracking included
  • Background replacement

Premium Users: Get free access to all features including image generation, segmentation, and media retrieval!

Bulk Discounts: Purchase 1000+ credits for 10% discount, 10000+ credits for 20% discount!

Rate Limiting

Understanding API rate limits and best practices

Rate Limits by Plan

Plan Requests/Minute Requests/Hour Concurrent
Free Tier 10 100 1
Premium 60 1000 5
Enterprise 200 5000 20

Rate Limit Headers

All responses include rate limit information:

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1634567890
X-RateLimit-Window: 60

Handling Rate Limits

Implement exponential backoff when rate limited:

import time
import requests

def generate_with_retry(prompt, max_retries=3):
    for attempt in range(max_retries):
 try:
 response = requests.post(
 'https://api.univence.com/v1/images/generations',
 headers={'X-API-Key': 'your-api-key'},
 json={'model': 'z-image-turbo', 'prompt': prompt}
 )
 
 if response.status_code == 429:
 reset_time = int(response.headers.get('X-RateLimit-Reset', 60))
 wait_time = min(reset_time, 60)
 print(f"Rate limited. Waiting {wait_time} seconds...")
 time.sleep(wait_time)
 continue
 
 response.raise_for_status()
 return response.json()
 
 except requests.exceptions.RequestException as e:
 if attempt == max_retries - 1:
 raise e
 time.sleep(2 ** attempt)  # Exponential backoff

Caching & Performance

Optimize your API usage with effective caching strategies

Media File Caching

Generated images and media files are cached for performance:

  • Generated Images: Cached for 24 hours
  • Segmentation Results: Cached for 7 days
  • Upscaled Images: Cached for 30 days
  • CDN Distribution: Global edge caching

Client-Side Caching Example

class MediaCache {
    constructor() {
 this.cache = new Map();
 this.ttl = 24 * 60 * 60 * 1000; // 24 hours
    }
    
    generateCacheKey(prompt, params) {
 return btoa(JSON.stringify({prompt, ...params}));
    }
    
    isValid(timestamp) {
 return Date.now() - timestamp < this.ttl;
    }
    
    async getOrGenerate(prompt, params, generator) {
 const key = this.generateCacheKey(prompt, params);
 const cached = this.cache.get(key);
 
 if (cached && this.isValid(cached.timestamp)) {
 return cached.data;
 }
 
 const result = await generator(prompt, params);
 this.cache.set(key, {
 data: result,
 timestamp: Date.now()
 });
 
 return result;
    }
}

Authentication Examples

Code examples for authenticating API requests

cURL Example

curl -X POST "https://api.univence.com/v1/images/generations" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{
    "model": "z-image-turbo",
    "prompt": "a beautiful sunset"
  }'

JavaScript/Node.js Example

const response = await fetch('https://api.univence.com/v1/images/generations', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your-api-key-here'
  },
  body: JSON.stringify({
    model: 'z-image-turbo',
    prompt: 'a beautiful sunset over mountains'
  })
});

const result = await response.json();

Python Example

import requests

url = "https://api.univence.com/v1/images/generations"
headers = {
    "Content-Type": "application/json",
    "X-API-Key": "your-api-key-here"
}
data = {
    "model": "z-image-turbo",
    "prompt": "a beautiful sunset over mountains"
}

response = requests.post(url, headers=headers, json=data)
result = response.json()

Complete Usage Examples

End-to-end examples for common use cases

Generate Image with Parameters

curl -X POST "https://api.univence.com/v1/images/generations" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "model": "z-image-turbo",
    "prompt": "a serene mountain landscape at sunset",
    "image_size": "1920x1080",
    "negative_prompt": "blurry, low quality, distorted",
    "num_inference_steps": 50,
    "guidance_scale": 7.5,
    "seed": 42
  }'

Batch Generation

curl -X POST "https://api.univence.com/v1/images/generations/batch" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "requests": [
 {"model": "z-image-turbo", "prompt": "a red rose"},
 {"model": "z-image-turbo", "prompt": "a blue rose"},
 {"model": "z-image-turbo", "prompt": "a white rose"}
    ],
    "response_format": "url"
  }'

Image Upscaling

async function upscaleImage(imageUrl) {
    const response = await fetch('https://api.univence.com/v1/images/upscale', {
 method: 'POST',
 headers: {
 'Content-Type': 'application/json',
 'X-API-Key': 'your-api-key'
 },
 body: JSON.stringify({
 image_url: imageUrl,
 upscale_factor: 4,
 model: 'realesrgan_4x',
 enhance_details: true,
 noise_reduction: true
 })
    });
    
    const result = await response.json();
    return result.data[0].url;
}

Background Removal

import requests

def remove_background(image_url):
    url = "https://api.univence.com/v1/images/remove-background"
    headers = {"X-API-Key": "your-api-key"}
    data = {
 "image_url": image_url,
 "edge_smooth": 5,
 "output_format": "png"
    }
    
    response = requests.post(url, headers=headers, json=data)
    result = response.json()
    return result['data'][0]['url']

Model Specifications

Available AI models and their capabilities

Z-Image-Turbo

Text-to-Image
Max Resolution: 2048×2048
Best For: General text-to-image generation

Delivers strong photorealistic image generation while maintaining excellent aesthetic quality.

Perfect for: Landscapes, portraits, abstract art, product images

LongCat-Image-Edit

Image-to-Image
Max Resolution: 2560×2560
Parameters: ~20B

Large-scale image editing model for advanced image manipulation and style transfer.

Perfect for: Image editing, style transfer, inpainting, photo enhancement

Best Practices

Guidelines for optimal API usage

Prompt Engineering

  • Be specific and descriptive in your prompts
  • Use artistic style references (e.g., "in the style of oil painting")
  • Include lighting and atmosphere details
  • Specify composition and framing preferences
  • Use negative prompts to avoid unwanted elements

Performance Optimization

  • Use batch generation for multiple images
  • Implement client-side caching to avoid duplicate requests
  • Choose appropriate image sizes for your use case
  • Monitor rate limit headers to avoid throttling
  • Use smaller inference steps for faster generation when quality isn't critical

Security Best Practices

  • Never expose API keys in client-side code
  • Use environment variables for API key storage
  • Implement proper error handling and logging
  • Validate user input before sending to API
  • Use HTTPS for all API communications

Cost Optimization

  • Use image_size parameter appropriately - larger images cost more credits
  • Batch requests are more cost-effective than individual requests
  • Cache generated images to avoid regeneration
  • Monitor credit usage regularly
  • Consider Premium plan for high-volume usage

Troubleshooting

Solutions to common issues

Issue: "Invalid API Key" Error

Solution: Verify your API key is correct and properly formatted. Generate a new key from your account dashboard if needed.

Issue: Slow Generation Times

Solution: Reduce num_inference_steps parameter, use smaller image sizes, or switch to z-image-turbo model for faster generation.

Issue: Rate Limit Exceeded

Solution: Implement exponential backoff, upgrade your plan for higher limits, or use batch requests to maximize efficiency.

Issue: Poor Image Quality

Solution: Increase num_inference_steps (50-100), adjust guidance_scale (7-12), use more specific prompts, or add negative prompts.

Issue: Upscaling Artifacts

Solution: Try different upscaling models (realesrgan_4x for photos, realesrgan_4x_anime for anime), enable noise_reduction and enhance_details.

Issue: Background Removal Not Working

Solution: Ensure image_url is publicly accessible, try adjusting edge_smooth parameter, or verify the image has clear foreground subjects.

Ready to Get Started?

Join thousands of developers creating amazing images with our AI API