DEV Community

diwushennian4955
diwushennian4955

Posted on

How to Generate Images with FLUX API in Python - Complete Guide 2026

FLUX is the current gold standard for AI image generation — photorealistic quality, precise prompt following, and production-grade reliability. But official API pricing can add up fast at scale.

In this guide, I'll show you how to integrate FLUX API in Python using advllmtrain.com — which provides FLUX model access at a fraction of official pricing, with the same API format.

What is FLUX API?

FLUX API is the programmatic interface to Black Forest Labs' (BFL) family of generative image models. Key models available in 2026:

Model Best For
flux-pro/v1.1 Fast & reliable standard
flux-pro/v1.1-ultra Ultra-high resolution (4MP)
flux-dev Open-source / fine-tuning
flux-schnell Real-time, sub-2s generation

Prerequisites

pip install requests
Enter fullscreen mode Exit fullscreen mode

Get your API key from advllmtrain.com — they offer FLUX Pro access at competitive pricing with a prepaid credit model.

Basic Image Generation

Here's the simplest way to generate an image with FLUX API:

import requests
import time

API_KEY = "your_advllmtrain_api_key"
BASE_URL = "https://advllmtrain.com/v1"

def generate_image(prompt: str, model: str = "fal-ai/flux-pro/v1.1") -> str:
    """Generate an image using FLUX API and return the image URL."""

    # Submit generation request
    response = requests.post(
        f"{BASE_URL}/images/generations",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "model": model,
            "prompt": prompt,
            "image_size": "landscape_4_3",
            "num_images": 1
        }
    )

    data = response.json()
    return data["data"][0]["url"]

# Generate your first image
image_url = generate_image(
    "A futuristic cityscape at sunset, photorealistic, 8K detail"
)
print(f"Generated image: {image_url}")
Enter fullscreen mode Exit fullscreen mode

Advanced: Async Generation with Polling

For high-quality models that take longer, use async polling:

import requests
import time

API_KEY = "your_advllmtrain_api_key"
BASE_URL = "https://advllmtrain.com/v1"

def generate_image_async(prompt: str, model: str = "fal-ai/flux-pro/v1.1-ultra") -> str:
    """Async generation with polling — for high-quality models."""

    # Step 1: Submit request
    response = requests.post(
        f"{BASE_URL}/images/generations",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={
            "model": model,
            "prompt": prompt,
            "image_size": "square_hd",
            "enable_safety_checker": True
        }
    )
    data = response.json()

    # If synchronous response, return directly
    if "data" in data:
        return data["data"][0]["url"]

    # Step 2: Poll for async result
    request_id = data.get("id")
    while True:
        result = requests.get(
            f"{BASE_URL}/requests/{request_id}",
            headers={"Authorization": f"Bearer {API_KEY}"}
        ).json()

        if result.get("status") == "completed":
            return result["output"]["images"][0]["url"]
        elif result.get("status") == "failed":
            raise Exception(f"Generation failed: {result}")

        time.sleep(2)

# Ultra-high resolution image
image_url = generate_image_async(
    "Professional product photo, white background, studio lighting",
    model="fal-ai/flux-pro/v1.1-ultra"
)
print(f"Ultra-res image: {image_url}")
Enter fullscreen mode Exit fullscreen mode

Batch Generation

Need to generate many images? Here's an async batch approach:

import asyncio
import aiohttp

async def generate_batch(prompts: list[str], api_key: str) -> list[str]:
    """Generate multiple images concurrently."""

    async with aiohttp.ClientSession() as session:
        async def generate_one(prompt: str) -> str:
            async with session.post(
                "https://advllmtrain.com/v1/images/generations",
                headers={"Authorization": f"Bearer {api_key}"},
                json={"model": "fal-ai/flux-pro/v1.1", "prompt": prompt}
            ) as resp:
                data = await resp.json()
                return data["data"][0]["url"]

        tasks = [generate_one(p) for p in prompts]
        return await asyncio.gather(*tasks)

# Generate 5 images concurrently
prompts = [
    "Mountain landscape at dawn",
    "Ocean sunset with dramatic clouds",
    "Dense forest with morning mist",
    "Desert dunes under starry sky",
    "Snowy peaks with aurora borealis"
]

urls = asyncio.run(generate_batch(prompts, API_KEY))
for i, url in enumerate(urls):
    print(f"Image {i+1}: {url}")
Enter fullscreen mode Exit fullscreen mode

Image-to-Image Refinement

FLUX supports img2img workflows — provide a reference image and transform it:

def refine_image(source_url: str, prompt: str) -> str:
    """Refine an existing image with a new prompt."""

    response = requests.post(
        f"{BASE_URL}/images/generations",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={
            "model": "fal-ai/flux-pro/v1.1",
            "prompt": prompt,
            "image_url": source_url,
            "image_size": "square_hd",
            "strength": 0.75  # How much to change (0=no change, 1=full regen)
        }
    )
    return response.json()["data"][0]["url"]

# Example: Transform product photo
refined = refine_image(
    source_url="https://your-cdn.com/raw-product.jpg",
    prompt="Professional studio lighting, white background, commercial photography"
)
Enter fullscreen mode Exit fullscreen mode

FLUX API Pricing Comparison 2026

Here's what you'll pay per image across providers:

Provider FLUX Pro/v1.1 FLUX Schnell Monthly Min
fal.ai (official) $0.05/megapixel $0.003/image None
Replicate $0.04/image $0.003/image None
advllmtrain.com ~$0.008–$0.010/image ~$0.001/image None

At 10,000 images/month:

  • fal.ai official: ~$500/month
  • advllmtrain.com: ~$80–$100/month

That's 80% savings for the same FLUX Pro quality.

Complete Working Example

Here's a full script you can run right now:

import requests
import time
import os
from pathlib import Path

API_KEY = os.environ.get("ADVLLM_API_KEY", "your_api_key_here")
BASE_URL = "https://advllmtrain.com/v1"

def generate_and_save(prompt: str, output_path: str = "output.jpg") -> str:
    """Generate an image and save it locally."""

    print(f"Generating: {prompt[:50]}...")

    response = requests.post(
        f"{BASE_URL}/images/generations",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "model": "fal-ai/flux-pro/v1.1",
            "prompt": prompt,
            "image_size": "landscape_16_9",
            "num_inference_steps": 28,
            "guidance_scale": 3.5,
            "num_images": 1,
            "enable_safety_checker": True
        }
    )

    if response.status_code != 200:
        raise Exception(f"API error {response.status_code}: {response.text}")

    data = response.json()
    image_url = data["data"][0]["url"]

    # Download and save
    img_response = requests.get(image_url)
    Path(output_path).write_bytes(img_response.content)

    print(f"✅ Saved to {output_path}")
    print(f"   URL: {image_url}")
    return image_url

if __name__ == "__main__":
    generate_and_save(
        "A serene Japanese garden with cherry blossoms, golden hour lighting, photorealistic",
        "japanese_garden.jpg"
    )
Enter fullscreen mode Exit fullscreen mode

Key Parameters Reference

Parameter Values Description
model fal-ai/flux-pro/v1.1, fal-ai/flux-pro/v1.1-ultra, fal-ai/flux-dev, fal-ai/flux/schnell Model variant
image_size square_hd, landscape_4_3, landscape_16_9, portrait_16_9 Output dimensions
num_inference_steps 1–50 (default 28) Quality vs speed tradeoff
guidance_scale 1–20 (default 3.5) Prompt adherence strength
num_images 1–4 Images per request
seed integer Reproducible generation

Conclusion

FLUX API is the best choice for production AI image generation in 2026. With advllmtrain.com, you get:

  • ✅ Same FLUX Pro quality at 80% lower cost
  • ✅ OpenAI-compatible API format
  • ✅ No monthly fees — prepaid credits
  • ✅ 200+ models on one endpoint (GPT-4o, Claude, Gemini, DALL-E 3, Stable Diffusion)

Get your API key and start generating: advllmtrain.com


Full pricing breakdown and advanced use cases: FLUX API Integration Guide 2026

Top comments (0)