API Documentation
Complete reference for ButterflyAPI's AI-powered image and video processing APIs. Access 12+ APIs with a single API key.
Quick Start Guide
Create an Account
Sign up at butterflyapi.com/auth/sign-up - you'll receive 100 free credits instantly.
Generate an API Key
Go to your Dashboard > API Keys and create a new key. Keep it secret!
Make Your First API Call
Use the example below to transform an image. Results are ready in seconds!
Your First API Call
curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "background-remove",
"input": {
"image_url": "https://images.unsplash.com/photo-1234567890"
}
}'Authentication
All API requests must include your API key in the Authorization header using the Bearer token format.
Authorization: Bearer sk_your_api_keyAPI Key Format
API keys start with sk_ followed by a unique identifier. Example: sk_butterfly_abc123xyz789
Base URL
https://butterflyapi.com/api/v1All endpoints are relative to this base URL. HTTPS is required for all requests.
Request Format
Most APIs use the unified /api/v1/run endpoint. Specify which API to use in the request body.
Standard Request Structure
{
"api": "api-name", // Required: Which API to use
"input": { // Required: API-specific parameters
"image_url": "...", // Most APIs require an image URL
"prompt": "...", // Some APIs accept prompts
// ... other parameters
}
}Response Structure
{
"jobId": "job_abc123xyz", // Unique job identifier
"status": "queued", // queued | processing | completed | failed
"creditsCharged": 5, // Credits deducted for this job
"outputUrl": "https://...", // Result URL (when completed)
"error": "..." // Error message (when failed)
}Credits & Pricing
Each API call costs a specific number of credits. Credits are deducted when a job starts. If a job fails due to our systems, credits are automatically refunded.
| API | Use Case | Credits |
|---|---|---|
| Text to Image | Generate images from text prompts | 3 |
| Image to Image | Transform images with AI | 5 |
| Cartoon Styles | Convert photos to cartoon art | 6 |
| Background Removal | Remove backgrounds from images | 2 |
| Upscale | Increase image resolution 2x or 4x | 4 |
| Face Restore | Enhance and restore faces | 3 |
| Image Enhance | Improve overall image quality | 3 |
| Image Caption | Generate descriptions of images | 2 |
| Watermark | Add watermarks to images | 1 |
| HTML to PDF | Convert HTML to PDF documents | 1 |
| Video Generation | 5s or 10s, Standard or Pro quality | 50-150 |
| CineFlow AI | Cinematic video with camera controls | 100 |
1 credit = £0.01. Purchase credits from the pricing page or enable auto-topup in your dashboard settings.
Image APIs
AI-powered image generation and transformation
Text to Image
3 creditsGenerate stunning images from text descriptions using state-of-the-art diffusion models. Perfect for creating product mockups, artwork, social media content, and creative visuals.
Best For
- • Creative artwork and illustrations
- • Product concept visualization
- • Social media content
- • Marketing materials
Supported Formats
- • Output: PNG, JPEG, WebP
- • Aspect ratios: 1:1, 16:9, 9:16, 4:3, 3:4
- • Max resolution: 1024x1024
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| prompt | string | Yes | Text description of the image to generate (max 500 chars) |
| negative_prompt | string | No | What to exclude from the image (e.g., "blurry, low quality") |
| aspect_ratio | string | No | 1:1, 16:9, 9:16, 4:3, 3:4 (default: 1:1) |
| seed | number | No | Random seed for reproducible results |
curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "text-to-image",
"input": {
"prompt": "A serene Japanese garden with cherry blossoms, koi pond, wooden bridge, golden hour lighting, highly detailed",
"negative_prompt": "blurry, low quality, distorted",
"aspect_ratio": "16:9"
}
}'Response
{
"jobId": "job_txt2img_abc123",
"status": "queued",
"creditsCharged": 5
}
// After polling, when completed:
{
"jobId": "job_txt2img_abc123",
"status": "completed",
"outputUrl": "https://cdn.butterflyapi.com/outputs/abc123.png",
"creditsCharged": 5,
"processingTimeMs": 8234
}Image to Image
5 creditsTransform existing images using AI. Change styles, add elements, modify scenes while preserving the original composition. The strength parameter controls how much the image changes.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_url | string | Yes | URL of the source image (HTTPS required) |
| prompt | string | Yes | Description of the desired transformation |
| strength | number | No | 0.1-1.0 - How much to transform (default: 0.7). Lower = subtle, higher = dramatic |
| negative_prompt | string | No | What to exclude from the result |
- 0.3-0.5: Subtle changes, keeps most of original
- 0.5-0.7: Balanced transformation (recommended)
- 0.7-1.0: Dramatic changes, may lose original details
curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "image-to-image",
"input": {
"image_url": "https://your-site.com/photo.jpg",
"prompt": "Transform into a watercolor painting with soft pastel colors",
"strength": 0.65,
"negative_prompt": "photorealistic, harsh colors"
}
}'Cartoon Styles
6 creditsTransform photos into 21 different copyright-safe cartoon and illustration styles. From stylized 3D to anime, graphic comic art, synthwave, and pop art.
Available Styles
| Style ID | Name | Description |
|---|---|---|
| stylized-3d | Stylized 3D | Expressive 3D animated character style with smooth surfaces and vibrant colors |
| anime | Anime | Japanese-style 2D animation look with clean linework and cel shading |
| graphic-comic | Graphic Comic | Bold graphic novel illustration with strong outlines and vibrant colors |
| classic-2d | Classic 2D | Traditional hand-drawn animation style with soft lines and warm tones |
| comic-space | Comic Space Explorer | Comic-style illustration depicting an intergalactic explorer in a cosmic setting |
| comic-superpower | Comic Superpower | Comic-style illustration portraying a powerful superhero character in action |
| pixel-16bit | 16-Bit Pixel Art | Retro 16-bit pixel art style with clean pixel edges and limited color palette |
| clay | Claymation | Stop-motion clay animation look with handcrafted textures and soft forms |
| voxel | Voxel | Blocky voxel-based illustration with cubic shapes and pixel textures |
| retro-cartoon | Retro Cartoon | Vintage mid-century cartoon style with simple shapes and flat colors |
| rubber-hose | Rubber Hose Cartoon | 1930s-style cartoon look with exaggerated proportions and pie-cut eyes |
| chibi | Chibi | Cute chibi-style characters with oversized heads and tiny bodies |
| watercolor | Watercolor | Soft watercolor and ink painting style with translucent washes |
| oil-painting | Oil Painting | Classic oil painting aesthetic with visible brush strokes |
| sketch | Pencil Sketch | Hand-drawn pencil sketch style with graphite linework |
| graffiti | Graffiti | Urban graffiti street art style with bold colors and spray textures |
| pop-art | Pop Art | Bold pop art poster style with flat colors and halftone patterns |
| synthwave | Synthwave | Retro-futuristic illustration with neon lighting and 1980s color palette |
| ligne-claire | Ligne Claire | Clean-line illustration style with uniform outlines and flat bold colors |
| low-poly | Low-Poly | Geometric illustration built from faceted polygonal shapes |
| noir | Film Noir | High-contrast black-and-white noir style with dramatic lighting |
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| style | string | Yes | One of the style IDs from the table above |
| inputImageUrl | string | Yes | URL of the photo to transform (HTTPS required) |
| strength | number | No | 0.1-0.95 - Transformation intensity (default varies by style) |
/api/v1/cartoon instead of the unified /run endpoint.curl -X POST https://butterflyapi.com/api/v1/cartoon \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"style": "stylized-3d",
"inputImageUrl": "https://your-site.com/portrait.jpg",
"strength": 0.75
}'Response
{
"success": true,
"data": {
"style": "stylized-3d",
"jobId": "job_cartoon_abc123",
"status": "completed",
"outputUrl": "https://cdn.butterflyapi.com/outputs/abc123.png",
"creditsUsed": 5
},
"requestId": "req_xyz789"
}Background Removal
2 creditsRemove backgrounds from images with pixel-perfect accuracy. Works great on people, products, animals, and objects. Returns a transparent PNG.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_url | string | Yes | URL of image to process |
curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "background-remove",
"input": {
"image_url": "https://your-site.com/product.jpg"
}
}'Upscale
4 creditsIncrease image resolution by 2x or 4x using AI upscaling. Adds realistic detail and sharpness without artifacts. Great for enlarging photos, artwork, and thumbnails.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_url | string | Yes | URL of image to upscale |
| scale | number | No | 2 or 4 (default: 2). 4x takes longer but produces larger output |
curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "upscale",
"input": {
"image_url": "https://your-site.com/small-image.jpg",
"scale": 4
}
}'Face Restore
3 creditsRestore and enhance faces in photos. Fixes blur, noise, compression artifacts, and aging. Perfect for restoring old family photos or enhancing low-quality portraits.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_url | string | Yes | URL of image with faces to restore |
curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "face-restore",
"input": {
"image_url": "https://your-site.com/old-photo.jpg"
}
}'Image Enhance
3 creditsAutomatically improve image quality - fixes exposure, color balance, sharpness, and noise. One-click enhancement for any photo.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_url | string | Yes | URL of image to enhance |
curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "image-enhance",
"input": {
"image_url": "https://your-site.com/photo.jpg"
}
}'Video APIs
Generate AI videos from images and text
Video Generation
50-150 creditsTransform static images into dynamic video clips. Choose between 5 or 10 second durations with Standard or Pro quality tiers.
Pricing Tiers
| Duration | Quality | Credits | Best For |
|---|---|---|---|
| 5 seconds | Standard | 50 | Quick previews, social clips |
| 5 seconds | Pro | 80 | Higher quality, smoother motion |
| 10 seconds | Standard | 90 | Longer clips, product demos |
| 10 seconds | Pro | 150 | Best quality, professional use |
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_url | string | Yes | URL of source image to animate |
| duration | number | Yes | 5 or 10 (seconds) |
| quality | string | No | "standard" or "pro" (default: standard) |
| prompt | string | No | Describe the motion or action |
| negative_prompt | string | No | What to avoid in the video |
curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "video-gen",
"input": {
"image_url": "https://your-site.com/portrait.jpg",
"duration": 5,
"quality": "pro",
"prompt": "gentle breeze blowing through hair, subtle smile"
}
}'CineFlow AI
100 creditsDirect the camera. Generate the shot.
720p (1280x720) • 25fps • Up to 6 seconds • Cinematic camera controls
Generate cinematic videos with precise camera control. Use bracketed commands in your prompts to control camera movements - pan, tilt, zoom, track, and more.
Camera Commands
Add commands in brackets like [Push in] or combine up to 3: [Pan left, Tilt up, Tracking shot]
Horizontal
Vertical
Depth
Special
Shot Recipes
Orbit Left
[Truck left, Pan right, Tracking shot]Orbit Right
[Truck right, Pan left, Tracking shot]Hero Rise
[Push in, Pedestal up]Reveal
[Pull out, Tilt up]Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| prompt | string | Yes | Scene description with camera commands in brackets |
| image_url | string | No | Optional source image (text-to-video if omitted) |
| prompt_optimizer | boolean | No | Auto-enhance prompts for better results (default: true) |
Example Prompts
[Push in] A lamb stands alone in a snowy field, snowflakes gently falling around it.[Pan left, Tilt up] A knight stands amid ruins, camera reveals burning city walls and dragon shadow in the sky.A man picks up an old book [Pedestal up], then begins reading by candlelight [Static shot].curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "video-director",
"input": {
"prompt": "[Push in] A lamb stands alone in a snowy field, snowflakes gently falling.",
"prompt_optimizer": true
}
}'Utility APIs
Document generation and analysis tools
Image Caption
2 creditsGenerate detailed descriptions of images using AI vision. Ask questions about image content, generate alt text, or extract information from photos and documents.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_url | string | Yes | URL of image to analyze |
| question | string | No | Question to ask about the image (default: "What is this image?") |
| context | string | No | Additional context to help generate better captions |
curl -X POST https://butterflyapi.com/api/v1/run \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"api": "image-caption",
"input": {
"image_url": "https://your-site.com/photo.jpg",
"question": "Describe this image in detail for accessibility"
}
}'Response
{
"jobId": "job_caption_abc123",
"status": "completed",
"output": "A golden retriever dog playing fetch in a sunny park with green grass and trees in the background. The dog is mid-jump catching a red frisbee.",
"creditsCharged": 2
}Watermark
1 creditAdd image or text watermarks to photos. Control position, opacity, scale, and margins. Perfect for branding, copyright protection, and proofing.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_url | string | Yes | URL of base image |
| watermark_image_url | string | One required | URL of watermark image (PNG with transparency) |
| watermark_text | string | One required | Text watermark (alternative to image) |
| position | string | No | bottom-right, bottom-left, top-right, top-left, center (default: bottom-right) |
| opacity | number | No | 0-100 percentage (default: 35) |
| scale | number | No | 0.05-1.0 size ratio (default: 0.25) |
| margin | number | No | 0-0.1 margin ratio (default: 0.03) |
curl -X POST https://butterflyapi.com/api/v1/watermark \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"image_url": "https://your-site.com/photo.jpg",
"watermark_image_url": "https://your-site.com/logo.png",
"position": "bottom-right",
"opacity": 50,
"scale": 0.2
}'HTML to PDF
1 creditConvert HTML, text, or web pages to high-quality PDFs. Perfect for invoices, reports, certificates, and document generation.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| html | string | One of three | HTML content to convert |
| text | string | One of three | Plain text to convert |
| url | string | One of three | Web page URL to convert |
| options.format | string | No | A4, A3, A5, Letter, Legal, Tabloid (default: A4) |
| options.landscape | boolean | No | Landscape orientation (default: false) |
| options.margin | object | No | { top, right, bottom, left } in mm or px |
curl -X POST https://butterflyapi.com/api/v1/pdf \
-H "Authorization: Bearer sk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"html": "<h1>Invoice #1234</h1><p>Amount: £99.99</p><p>Due: 2024-02-01</p>",
"options": {
"format": "A4",
"margin": { "top": "20mm", "bottom": "20mm" }
}
}' \
--output invoice.pdfReference
Technical details and troubleshooting
Job Status & Polling
Most APIs process asynchronously. After submitting a job, poll the status endpoint until completion.
/api/v1/jobs/:jobIdJob Statuses
Polling Example
async function pollForResult(jobId, apiKey) {
const maxAttempts = 60;
const pollInterval = 2000; // 2 seconds
for (let i = 0; i < maxAttempts; i++) {
const response = await fetch(`https://butterflyapi.com/api/v1/jobs/${jobId}`, {
headers: { 'Authorization': `Bearer ${apiKey}` },
});
const data = await response.json();
if (data.status === 'completed') {
return data.outputUrl;
}
if (data.status === 'failed') {
throw new Error(data.error || 'Job failed');
}
// Wait before polling again
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for job completion');
}
// Usage
const outputUrl = await pollForResult('job_abc123', 'sk_your_api_key');
console.log('Result:', outputUrl);Error Codes
| Code | Meaning | Resolution |
|---|---|---|
| 200 | Success | Request completed successfully |
| 400 | Bad Request | Check required parameters and format |
| 401 | Unauthorized | Invalid or missing API key |
| 402 | Payment Required | Insufficient credits - purchase more |
| 404 | Not Found | Invalid endpoint or job ID |
| 429 | Rate Limited | Too many requests - wait and retry |
| 500 | Server Error | Our issue - retry or contact support |
Rate Limits
| Tier | Limit | Burst |
|---|---|---|
| All Users | 60 requests/minute | Per API key |
| Enterprise | Custom | Contact us |
Rate limits apply per API key. If you exceed the limit, you'll receive a 429 error. Wait 60 seconds before retrying.
Embed Widget
Add AI image generation directly to your website with our embeddable widget. Perfect for e-commerce, print-on-demand, and SaaS platforms.
Quick Setup
Configure Your Widget
Go to Dashboard > Embed Widget and set up your allowed domains, enabled tools, and custom theming.
Generate a Session Token
Call our session endpoint from your backend to get a secure, short-lived token. Never expose your API key to the browser.
Embed the Iframe
Add the iframe to your page with the session token. Your customers can now generate images!
Generate Session Token
Call this endpoint from your backend server to get a secure session token:
POST https://butterflyapi.com/api/embed/session
Authorization: Bearer sk_your_api_key
Content-Type: application/json
{
"domain": "yoursite.com",
"metadata": {
"orderId": "order_12345",
"customerId": "cust_abc"
}
}
// Response
{
"token": "emb_session_xyz123...",
"expiresAt": "2025-01-01T12:00:00Z"
}Embed Code
Add this iframe to your website, replacing the token with your session token:
<iframe
src="https://butterflyapi.com/embed/studio?token=YOUR_SESSION_TOKEN"
width="100%"
height="600"
frameborder="0"
allow="clipboard-write"
></iframe>Configuration Options
| Setting | Description |
|---|---|
| Allowed Domains | List of domains authorized to use your widget |
| Enabled Tools | Choose which AI tools are available (text-to-image, background remove, etc.) |
| Theme Colors | Customize primary color, background, and text colors |
| File Naming | Template for generated file names (e.g., {orderId}_{timestamp}.png) |
| Webhook URL | Receive generated images via POST request to your backend |
| Rate Limit | Max requests per hour per domain |
PostMessage API
Listen for events from the embedded widget in your parent page:
window.addEventListener('message', (event) => {
// Verify origin for security
if (event.origin !== 'https://butterflyapi.com') return;
const { type, data } = event.data;
switch (type) {
case 'generation_complete':
console.log('Image URL:', data.outputUrl);
console.log('Metadata:', data.metadata);
break;
case 'generation_error':
console.error('Error:', data.error);
break;
case 'download':
console.log('User downloaded:', data.filename);
break;
}
});E-Commerce Integration
For Shopify and WooCommerce, we provide webhook endpoints that automatically attach generated images to orders:
Shopify
Images are attached as order metafields for easy access in your fulfillment workflow.
View Shopify Guide →SDKs & Libraries
Use our official SDKs for easier integration:
View all integrations and plugins including WordPress, Zapier, and more.
Troubleshooting
Need Help?
Can't find what you're looking for? Our team is here to help.