> ## Documentation Index
> Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# FLUX API quickstart: Generate images with CometAPI

> Create a FLUX.2 Pro image task through CometAPI, poll until it is Ready, and download the resulting PNG.

## What you will build

You will submit a `1280x768` PNG task to FLUX.2 Pro, store the returned task `id`, poll `GET /flux/v1/get_result`, and download `result.sample` when the task becomes `Ready`.

## Prerequisites

* A CometAPI API key stored in `COMETAPI_KEY`
* `curl` and `jq`, Python 3.10+ with `requests`, or Node.js 18+
* Access to `flux-2-pro` on your CometAPI account

## Endpoints and authentication

Submit the task:

```text theme={null}
POST https://api.cometapi.com/flux/v1/flux-2-pro
```

Poll with the top-level `id` returned by the create response:

```text theme={null}
GET https://api.cometapi.com/flux/v1/get_result?id=<task_id>
```

Authenticate both CometAPI requests with:

```text theme={null}
Authorization: Bearer $COMETAPI_KEY
```

## Code examples

<CodeGroup>
  ```bash cURL theme={null}
  set -e

  CREATE_RESPONSE=$(curl --max-time 60 -fSs https://api.cometapi.com/flux/v1/flux-2-pro \
    -H "Authorization: Bearer $COMETAPI_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "prompt": "A clean editorial photograph of a red ceramic teapot on a pale blue table, a small yellow lemon on the right, soft window light, no text.",
      "width": 1280,
      "height": 768,
      "output_format": "png",
      "seed": 424242
    }')

  TASK_ID=$(printf "%s" "$CREATE_RESPONSE" | jq -r '.id')

  for ATTEMPT in $(seq 1 60); do
    RESULT=$(curl --max-time 30 -fSs "https://api.cometapi.com/flux/v1/get_result?id=$TASK_ID" \
      -H "Authorization: Bearer $COMETAPI_KEY")
    STATUS=$(printf "%s" "$RESULT" | jq -r '.status')
    echo "status: $STATUS"

    case "$STATUS" in
      Ready)
        IMAGE_URL=$(printf "%s" "$RESULT" | jq -r '.result.sample')
        curl --max-time 60 -fL "$IMAGE_URL" -o flux-result.png
        exit 0
        ;;
      Error|Failed|Failure|"Task not found"|"Request Moderated"|"Content Moderated"|failed|failure)
        echo "FLUX task failed: $STATUS" >&2
        exit 1
        ;;
    esac

    sleep 5
  done

  echo "FLUX task did not finish in time" >&2
  exit 1
  ```

  ```python Python theme={null}
  import os
  import time
  from pathlib import Path

  import requests

  headers = {"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]}
  payload = {
      "prompt": (
          "A clean editorial photograph of a red ceramic teapot on a pale blue "
          "table, a small yellow lemon on the right, soft window light, no text."
      ),
      "width": 1280,
      "height": 768,
      "output_format": "png",
      "seed": 424242,
  }

  create_response = requests.post(
      "https://api.cometapi.com/flux/v1/flux-2-pro",
      headers={**headers, "Content-Type": "application/json"},
      json=payload,
      timeout=60,
  )
  create_response.raise_for_status()
  task_id = create_response.json()["id"]

  failure_statuses = {
      "Error",
      "Failed",
      "Failure",
      "Task not found",
      "Request Moderated",
      "Content Moderated",
      "failed",
      "failure",
  }

  for _ in range(60):
      result_response = requests.get(
          "https://api.cometapi.com/flux/v1/get_result",
          headers=headers,
          params={"id": task_id},
          timeout=30,
      )
      result_response.raise_for_status()
      result = result_response.json()
      status = result.get("status")
      print(status)

      if status == "Ready":
          image_response = requests.get(result["result"]["sample"], timeout=60)
          image_response.raise_for_status()
          Path("flux-result.png").write_bytes(image_response.content)
          break
      if status in failure_statuses:
          raise RuntimeError(f"FLUX task failed: {status}")

      time.sleep(5)
  else:
      raise TimeoutError("FLUX task did not finish in time")
  ```

  ```javascript Node.js theme={null}
  import fs from "node:fs/promises";

  const authHeaders = {
    Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
  };

  const createResponse = await fetch(
    "https://api.cometapi.com/flux/v1/flux-2-pro",
    {
      method: "POST",
      headers: { ...authHeaders, "Content-Type": "application/json" },
      signal: AbortSignal.timeout(60_000),
      body: JSON.stringify({
        prompt:
          "A clean editorial photograph of a red ceramic teapot on a pale blue table, a small yellow lemon on the right, soft window light, no text.",
        width: 1280,
        height: 768,
        output_format: "png",
        seed: 424242,
      }),
    },
  );

  if (!createResponse.ok) throw new Error(await createResponse.text());
  const { id } = await createResponse.json();

  const failureStatuses = new Set([
    "Error",
    "Failed",
    "Failure",
    "Task not found",
    "Request Moderated",
    "Content Moderated",
    "failed",
    "failure",
  ]);
  let completed = false;

  for (let attempt = 0; attempt < 60; attempt += 1) {
    const resultResponse = await fetch(
      `https://api.cometapi.com/flux/v1/get_result?id=${encodeURIComponent(id)}`,
      { headers: authHeaders, signal: AbortSignal.timeout(30_000) },
    );
    if (!resultResponse.ok) throw new Error(await resultResponse.text());

    const result = await resultResponse.json();
    console.log(result.status);

    if (result.status === "Ready") {
      const imageResponse = await fetch(result.result.sample, {
        signal: AbortSignal.timeout(60_000),
      });
      if (!imageResponse.ok) throw new Error(await imageResponse.text());
      await fs.writeFile(
        "flux-result.png",
        Buffer.from(await imageResponse.arrayBuffer()),
      );
      completed = true;
      break;
    }
    if (failureStatuses.has(result.status)) {
      throw new Error(`FLUX task failed: ${result.status}`);
    }

    await new Promise((resolve) => setTimeout(resolve, 5000));
  }

  if (!completed) throw new Error("FLUX task did not finish in time");
  ```
</CodeGroup>

## How the flow works

The create endpoint returns a top-level task `id`; it can also return `status: "processing"`. Poll the CometAPI result endpoint with that `id`. `Ready` is the successful terminal state. Treat known error and moderation states as failures, and keep polling other states only until your client timeout.

Use `result.sample` only to download the finished image. It is a temporary URL and should not be used as durable application storage.

## Common parameters

| Parameter            | Use                                                                                                                            |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `model` path segment | FLUX.2 model ID in the URL path. This quickstart uses `flux-2-pro`; check [Models](/overview/models) for account availability. |
| `prompt`             | Required image description or edit instruction.                                                                                |
| `width` / `height`   | Requested output dimensions in pixels.                                                                                         |
| `output_format`      | Format supported by the selected model. This quickstart uses `png`.                                                            |
| `seed`               | Optional seed value. The result can report the used seed; that field alone does not establish repeatable output.               |
| `input_image`        | Public HTTPS reference-image URL for editing.                                                                                  |
| `input_image_2`      | Second public HTTPS reference-image URL for FLUX.2 Pro; also send `input_image`.                                               |

## Troubleshooting

<AccordionGroup>
  <Accordion title="The task stays in a processing state">
    Continue polling within a bounded retry loop. If the client timeout is reached, keep the task ID for later inspection and report the request as timed out rather than successful.
  </Accordion>

  <Accordion title="The image URL no longer works">
    Download `result.sample` promptly after the task becomes `Ready`, then place the image in storage that your application controls.
  </Accordion>

  <Accordion title="A request field has no effect">
    Start with the fields in the API reference. Treat additional model-specific controls as unverified until you confirm that the selected CometAPI route preserves and applies them.
  </Accordion>
</AccordionGroup>

## Next steps

* Read the [Generate a FLUX image API reference](/api/image/flux/flux-generate-image).
* Poll results with [Get a FLUX image result](/api/image/flux/flux-query).
* Find available FLUX models in [Models](/overview/models).
