> ## 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 빠른 시작: CometAPI로 이미지 생성

> CometAPI를 통해 Flux 이미지 작업을 생성하고, 생성된 이미지를 폴링한 뒤 URL이 만료되기 전에 결과를 다운로드합니다.

## 만들 내용

`POST /flux/v1/flux-dev`로 Flux 이미지 생성 작업을 만들고, `GET /flux/v1/get_result`를 폴링한 다음, 작업이 준비되면 생성된 이미지 URL을 다운로드합니다.

## 사전 준비

* `COMETAPI_KEY`에 저장된 CometAPI API 키
* `requests`가 설치된 Python 3.10+ 또는 Node.js 18+
* Flux API 레퍼런스 또는 [Models](/ko/overview/models)의 Flux model path

## API 키, base URL, 인증

Flux 생성은 URL path에서 모델 이름을 사용합니다:

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

task ID로 결과 엔드포인트를 폴링합니다:

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

Bearer 토큰으로 인증합니다:

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

## 코드 예제

아래 탭에서 cURL, Python, Node.js의 복사 가능한 예제를 사용할 수 있습니다.

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.cometapi.com/flux/v1/flux-dev \
    -H "Authorization: Bearer $COMETAPI_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "prompt": "A paper boat floating on calm water at sunrise.",
      "width": 512,
      "height": 512
    }'

  curl "https://api.cometapi.com/flux/v1/get_result?id=<task_id>" \
    -H "Authorization: Bearer $COMETAPI_KEY"
  ```

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

  import requests

  api_key = os.environ["COMETAPI_KEY"]
  headers = {"Authorization": f"Bearer {api_key}"}

  create_response = requests.post(
      "https://api.cometapi.com/flux/v1/flux-dev",
      headers={**headers, "Content-Type": "application/json"},
      json={
          "prompt": "A paper boat floating on calm water at sunrise.",
          "width": 512,
          "height": 512,
      },
      timeout=60,
  )
  create_response.raise_for_status()
  task_id = create_response.json()["id"]

  for _ in range(30):
      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()
      if result.get("status") == "Ready":
          image_url = result["result"]["sample"]
          image_bytes = requests.get(image_url, timeout=60).content
          Path("flux-result.jpeg").write_bytes(image_bytes)
          break
      if result.get("status") == "Task not found":
          raise RuntimeError("Flux task was not found")
      time.sleep(2)
  else:
      raise TimeoutError("Flux task did not finish in time")
  ```

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

  const headers = {
    Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
    "Content-Type": "application/json",
  };

  const createResponse = await fetch("https://api.cometapi.com/flux/v1/flux-dev", {
    method: "POST",
    headers,
    body: JSON.stringify({
      prompt: "A paper boat floating on calm water at sunrise.",
      width: 512,
      height: 512,
    }),
  });

  if (!createResponse.ok) {
    throw new Error(await createResponse.text());
  }

  const { id } = await createResponse.json();

  for (let attempt = 0; attempt < 30; attempt += 1) {
    const resultResponse = await fetch(
      `https://api.cometapi.com/flux/v1/get_result?id=${encodeURIComponent(id)}`,
      { headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` } },
    );

    if (!resultResponse.ok) {
      throw new Error(await resultResponse.text());
    }

    const result = await resultResponse.json();
    if (result.status === "Ready") {
      const imageResponse = await fetch(result.result.sample);
      const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
      await fs.writeFile("flux-result.jpeg", imageBuffer);
      break;
    }
    if (result.status === "Task not found") {
      throw new Error("Flux task was not found");
    }
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
  ```
</CodeGroup>

## 흐름 설명

Flux 생성은 비동기식입니다. 생성 엔드포인트는 작업 `id`를 반환합니다. `status`가 `Ready`가 될 때까지 `/flux/v1/get_result?id=<task_id>`를 폴링한 다음, `result.sample`을 다운로드하세요.

Flux 결과 URL은 시간 제한이 있습니다. 애플리케이션에서 지속적으로 접근해야 하는 경우 완료된 이미지를 자체 스토리지에 복사하세요.

## 공통 파라미터

| Parameter            | 용도                                              |
| -------------------- | ----------------------------------------------- |
| `model` path segment | URL 경로의 Flux 모델 변형이며, 참조 예제로는 `flux-dev`가 있습니다. |
| `prompt`             | 필수 텍스트 프롬프트(Prompt)입니다.                         |
| `width` / `height`   | 픽셀 단위의 출력 크기입니다. API 레퍼런스에 모델별 범위가 안내되어 있습니다.   |
| `seed`               | 선택적 재현성 제어 값입니다.                                |
| `output_format`      | 선택한 Flux 모델이 지원하는 경우 요청하는 출력 이미지 형식입니다.         |
| `webhook_url`        | 지원되는 Flux 워크플로를 위한 선택적 완료 알림 URL입니다.            |

## 문제 해결 / FAQ

<AccordionGroup>
  <Accordion title="작업이 계속 pending 상태로 유지됩니다">
    재시도 횟수를 제한한 루프와 타임아웃을 두고 계속 폴링하세요. 나중에 작업을 확인할 수 있도록 task ID를 저장해 두세요.
  </Accordion>

  <Accordion title="이미지 URL이 만료되었습니다">
    작업이 `Ready` 상태가 되면 곧바로 `result.sample`을 다운로드한 다음, 이미지를 자체 스토리지에 저장하세요.
  </Accordion>

  <Accordion title="Flux 파라미터가 실패합니다">
    Flux 파라미터 지원은 모델 variant에 따라 다릅니다. `prompt`, `width`, `height`부터 시작한 뒤, 선택 필드를 추가하기 전에 Flux API 레퍼런스를 확인하세요.
  </Accordion>
</AccordionGroup>

## 다음 단계

* [Flux generate image API reference](/api/image/flux/flux-generate-image)를 읽어보세요.
* [Get Flux image result](/api/image/flux/flux-query)로 결과를 폴링하세요.
* [Models](/ko/overview/models)에서 Flux 모델을 찾아보세요.
* [Estimate request cost before calling a model](/ko/guides/how-to-estimate-cost-before-calling-a-model)로 비용을 예측해 보세요.
