โ† Back to blog

AI Image Generation API: Text-to-Image (FLUX.1 dev) for AI Agents

July 14, 2026 ยท Eric ยท 6 min read

You describe it โ€” the API generates it. Photorealistic images, illustrations, concept art, product mockups, logos, characters โ€” whatever you can put into words, Agent Media Tools can create it using FLUX.1 dev under the hood.

This guide walks through the complete image generation API โ€” endpoint, parameters, synchronous and async modes, polling, pricing, and full code examples in curl, Python, and from the MCP server.

How It Works

The image generation API is a REST endpoint that queues jobs on fal.ai's FLUX.1 dev model. You send a text prompt, and the API returns either an immediate result (wait mode) or a job ID you can poll for completion.

Behind the scenes, FLUX.1 dev runs 28 inference steps (configurable up to 50) on the GPU cluster, producing a high-resolution 1024ร—1024 image in roughly 5โ€“15 seconds.

You need an API key โ€” generate one free from the account panel (Account โ†’ API Keys). Free accounts can add purchased credits; Pro and Builder include a shared pool of 300 monthly media credits.

API Reference

EndpointPOST /api/agent/generate-image
AuthAuthorization: Bearer <agent-key>
Content-Typeapplication/json
PollingGET /api/agent/generate-image/:id (same Bearer auth)

Request Body Parameters

ParameterRequiredDefaultDescription
promptโœ… Yesโ€”Text description (max 2000 characters). What you want the AI to draw.
image_sizeNolandscape_4_3Aspect ratio. Options: square_hd, square, portrait_4_3, portrait_16_9, landscape_4_3, landscape_16_9
num_imagesNo1Number of images to generate (1โ€“4)
num_inference_stepsNo28Quality vs speed tradeoff (1โ€“50). Higher = better quality but slower.
seedNoRandomDeterministic seed for reproducible results
waitNofalseIf true, blocks until generation finishes and returns the result inline

Response Shape

When wait: true, a successful response looks like this:

{
  "success": true,
  "job_id": "abc123-def456",
  "status": "completed",
  "result": {
    "images": [
      {
        "url": "https://v3.fal.media/files/.../image_0.png",
        "width": 1024,
        "height": 1024,
        "content_type": "image/png"
      }
    ],
    "timings": {
      "inference": 8.2,
      "queue": 0.3
    },
    "seed": 173459201
  },
  "billing": {
    "num_images": 1,
    "credit_cost_per_image": 3,
    "credits_required": 0,
    "premium_free_credits": 3
  },
  "credits_remaining": 154
}

Without wait (the default), the API returns 202 Accepted and you poll the polling URL for the result.

curl Examples

๐Ÿ’ก Windows users: Run these from Git Bash or WSL โ€” PowerShell's curl is an alias for Invoke-WebRequest. Or use Invoke-RestMethod with the same URL/body.

Basic Image Generation (Sync)

Generate one image with default settings, waiting for the result:

curl -s -X POST https://agentmediatools.com/api/agent/generate-image \
  -H "Authorization: Bearer mt_..." \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A cyberpunk fox with neon blue fur, digital rain in background, cinematic lighting",
    "wait": true
  }'

Async Mode (Fire and Poll)

Kick off the job without waiting, then poll for the result:

# Step 1 โ€” start the job
JOB=$(curl -s -X POST https://agentmediatools.com/api/agent/generate-image \
  -H "Authorization: Bearer mt_..." \
  -H "Content-Type: application/json" \
  -d '{"prompt": "A majestic dragon flying over a medieval castle at sunset"}')

JOB_ID=$(echo "$JOB" | grep -o '"job_id":"[^"]*"' | cut -d'"' -f4)

# Step 2 โ€” poll until done
while :; do
  RESULT=$(curl -s https://agentmediatools.com/api/agent/generate-image/$JOB_ID \
    -H "Authorization: Bearer mt_...")
  STATUS=$(echo "$RESULT" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
  echo "Status: $STATUS"
  [ "$STATUS" = "completed" ] || [ "$STATUS" = "failed" ] && break
  sleep 2
done

echo "$RESULT" | python3 -m json.tool

Batch of 4 Images with Custom Size

curl -s -X POST https://agentmediatools.com/api/agent/generate-image \
  -H "Authorization: Bearer mt_..." \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A minimalist logo for a tech startup, geometric shapes, clean white background",
    "num_images": 4,
    "image_size": "square_hd",
    "seed": 42,
    "wait": true
  }'

Python Examples

Simple Sync Call

import requests
import json

API_KEY = "mt_..."
API_URL = "https://agentmediatools.com/api/agent/generate-image"

resp = requests.post(API_URL, headers={
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}, json={
    "prompt": "A cozy cabin in a snowy forest at night, warm light from windows, photorealistic",
    "image_size": "landscape_16_9",
    "wait": True
})

data = resp.json()
if data.get("success"):
    for img in data["result"]["images"]:
        print(f"Generated: {img['url']}")
else:
    print(f"Error: {data.get('error')}")

Async Helper with Polling

import requests
import time
import sys

API_KEY = "mt_..."
BASE = "https://agentmediatools.com/api/agent"

def generate_image(prompt, **kwargs):
    """Submit an image job and poll until complete."""
    body = {"prompt": prompt, **kwargs}
    resp = requests.post(
        f"{BASE}/generate-image",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json=body
    )
    job = resp.json()
    job_id = job.get("job_id")
    if not job_id:
        print(f"Submit failed: {job}")
        return None

    print(f"Job {job_id} submitted โ€” polling...")
    while True:
        time.sleep(2)
        poll = requests.get(
            f"{BASE}/generate-image/{job_id}",
            headers={"Authorization": f"Bearer {API_KEY}"}
        ).json()

        status = poll.get("job", {}).get("status")
        print(f"  Status: {status}")
        if status == "completed":
            return poll["job"]["result"]
        if status == "failed":
            print(f"  Failed: {poll['job'].get('error_message')}")
            return None

# Usage
result = generate_image(
    "A surreal landscape with floating islands, waterfalls falling into the sky",
    image_size="portrait_16_9",
    num_images=2,
    num_inference_steps=30
)

if result:
    for img in result["images"]:
        print(f"โ†’ {img['url']}")

Using the MCP Server

If you're running the Agent Media Tools MCP server, image generation is available as the generate_image tool. In Claude Desktop, Cursor, or any MCP-compatible client:

Generate an image of a cat wearing a space helmet, floating in zero gravity, with Earth visible through a window.

The MCP tool accepts the same parameters โ€” prompt, image_size, num_images, seed, and wait. By default it waits for the result so you get the images inline in your chat.

{
  "content": [
    {
      "type": "text",
      "text": "{\n  \"success\": true,\n  \"job_id\": \"...\",\n  \"status\": \"completed\",\n  \"result\": {\n    \"images\": [{\n      \"url\": \"https://v3.fal.media/files/.../image_0.png\",\n      \"width\": 1024,\n      \"height\": 1024\n    }],\n    \"seed\": 891234567\n  }\n}"
    }
  ]
}

Aspect Ratio Guide

Size KeyOrientationBest For
square_hd1:1 SquareProfile pics, thumbnails, logos, social media posts
square1:1 SquareStandard square (slightly smaller than HD)
portrait_4_34:3 PortraitBook covers, posters, iPad wallpapers
portrait_16_99:16 PortraitPhone wallpapers, Instagram Stories, TikTok
landscape_4_34:3 LandscapeStandard photographs, presentations, slides
landscape_16_916:9 LandscapeDesktop wallpapers, YouTube thumbnails, hero banners

Pricing & Credits

Each image costs 3 credits. Free accounts use purchased credits. Pro and Builder accounts include a shared pool of 300 monthly media credits, and every plan can add purchased credit packs.

PlanMonthly Free CreditsImages IncludedPurchase More?
FreeNone includedUses purchased creditsYes
Pro / Builder300 shared media creditsUp to ~100 images if the pool is used only for imagesYes

Purchased credits do not expire; included monthly media credits reset with the monthly allowance. The poll endpoint (GET /api/agent/generate-image/:id) does not cost extra โ€” credits are reserved on submission.

Prompt Tips for Best Results

FLUX.1 dev responds well to specific, descriptive prompts. Here are proven patterns:

Real-World Workflow

Here's a complete automation using the async polling pattern above:

  1. An AI content agent writes a blog post and identifies 3 illustration prompts
  2. The agent submits all 3 prompts simultaneously (parallel requests)
  3. Each returns a job_id immediately
  4. A polling loop waits for all 3 jobs to complete
  5. The agent downloads the images and inserts them into the blog post
  6. A webhook notifies the CMS that visuals are ready

Because each image costs 3 credits and takes ~10 seconds, a batch of 3 images costs 9 credits and completes in roughly 15 seconds end-to-end.

What About the MCP Server?

If you're already running the MCP server, image generation works out of the box. The MCP tool generate_image wraps the same API โ€” just set your MEDIA_TOOL_AGENT_KEY environment variable and describe what you want to see.

See the Claude MCP setup guide for installation steps.

Related Guides

Start Generating Images Now

Create a free account at agentmediatools.com, grab your API key from Account โ†’ API Keys, and add credits when you are ready to generate. No card is required to create the account or explore the free toolkit.

โ†’ Visit Agent Media Tools  ยท  ๐ŸŽจ Image Generation UI  ยท  ๐Ÿ’ฌ Discord

Tags: image generation, FLUX.1 dev, text-to-image, AI art, agent API, MCP, FLUX, stable diffusion, prompt engineering