> ## 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.

# Kling API 빠른 시작: CometAPI로 비디오 생성

> CometAPI를 통해 Kling 텍스트-비디오 작업을 생성하고, 작업 상태를 폴링하며, 콜백 기반 완료 처리를 다룹니다.

## 만들 내용

Kling 텍스트-비디오 작업을 제출하고, 반환된 작업 ID를 저장한 뒤, 해당 Kling 작업 엔드포인트를 폴링하고, 푸시 알림을 위해 언제 `callback_url`을 추가할지 결정하게 됩니다.

## 사전 요구 사항

* `COMETAPI_KEY`에 저장된 CometAPI API 키
* `requests`가 설치된 Python 3.10+ 또는 Node.js 18+
* 폴링을 위한 서버 측 워커 또는 웹훅용 HTTPS 콜백 엔드포인트

## API 키, 기본 URL, 인증

다음으로 Kling 텍스트-비디오 작업을 생성합니다:

```text theme={null}
POST https://api.cometapi.com/kling/v1/videos/text2video
```

다음으로 작업을 폴링합니다:

```text theme={null}
GET https://api.cometapi.com/kling/v1/videos/text2video/<task_id>
```

Bearer 토큰으로 인증합니다:

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

## 코드 예제

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

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.cometapi.com/kling/v1/videos/text2video \
    -H "Authorization: Bearer $COMETAPI_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "prompt": "A small ceramic cup on a wooden table, steam rising in soft morning light",
      "model_name": "kling-v3",
      "mode": "std",
      "duration": "5",
      "sound": "off"
    }'

  curl "https://api.cometapi.com/kling/v1/videos/text2video/<task_id>" \
    -H "Authorization: Bearer $COMETAPI_KEY"
  ```

  ```python Python theme={null}
  import os
  import time

  import requests

  api_key = os.environ["COMETAPI_KEY"]
  headers = {
      "Authorization": f"Bearer {api_key}",
      "Content-Type": "application/json",
  }

  create_response = requests.post(
      "https://api.cometapi.com/kling/v1/videos/text2video",
      headers=headers,
      json={
          "prompt": "A small ceramic cup on a wooden table, steam rising in soft morning light",
          "model_name": "kling-v3",
          "mode": "std",
          "duration": "5",
          "sound": "off",
      },
      timeout=60,
  )
  create_response.raise_for_status()
  task_id = create_response.json()["data"]["task_id"]

  for _ in range(60):
      task_response = requests.get(
          f"https://api.cometapi.com/kling/v1/videos/text2video/{task_id}",
          headers={"Authorization": f"Bearer {api_key}"},
          timeout=30,
      )
      task_response.raise_for_status()
      task = task_response.json()["data"]
      if task["task_status"] in {"succeed", "failed"}:
          print(task)
          break
      time.sleep(5)
  else:
      raise TimeoutError("Kling task did not finish in time")
  ```

  ```javascript Node.js theme={null}
  const createResponse = await fetch(
    "https://api.cometapi.com/kling/v1/videos/text2video",
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        prompt: "A small ceramic cup on a wooden table, steam rising in soft morning light",
        model_name: "kling-v3",
        mode: "std",
        duration: "5",
        sound: "off",
      }),
    },
  );

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

  const created = await createResponse.json();
  const taskId = created.data.task_id;

  for (let attempt = 0; attempt < 60; attempt += 1) {
    const taskResponse = await fetch(
      `https://api.cometapi.com/kling/v1/videos/text2video/${taskId}`,
      { headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` } },
    );

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

    const task = (await taskResponse.json()).data;
    if (["succeed", "failed"].includes(task.task_status)) {
      console.log(task);
      break;
    }
    await new Promise((resolve) => setTimeout(resolve, 5000));
  }
  ```
</CodeGroup>

## 흐름 설명

Kling 비디오 생성은 비동기 방식입니다. create 엔드포인트는 `data.task_id`를 반환합니다. `data.task_status`가 `succeed` 또는 `failed`에 도달할 때까지 `GET /kling/v1/videos/text2video/<task_id>`를 폴링하세요. 작업이 성공하면, 지속적으로 액세스해야 하는 경우 `data.task_result`의 완료된 asset URL을 자체 스토리지에 복사하세요.

직접 제어하는 HTTPS 엔드포인트로 작업 상태 업데이트를 푸시받고 싶다면 `callback_url`을 추가하세요. 상태 정합성 확인과 누락된 callback 전달에 대비해 폴링도 계속 사용할 수 있도록 유지하세요.

## 일반 매개변수

| Parameter      | 용도                                             |
| -------------- | ---------------------------------------------- |
| `prompt`       | 비디오 작업용 텍스트 프롬프트(Prompt)입니다.                   |
| `model_name`   | Kling model ID입니다. 참조 예제에서는 `kling-v3`를 사용합니다. |
| `mode`         | 생성 모드입니다. 더 높은 비용의 모드를 테스트하기 전에 `std`로 시작하세요.  |
| `duration`     | 출력 길이입니다. 참조 페이지에서는 첫 요청에 `5`를 사용합니다.          |
| `sound`        | 지원되는 모델 트랙에서 오디오 없는 결정적 첫 요청을 위해 `off`를 사용하세요. |
| `callback_url` | 작업 상태 callback용 선택적 HTTPS URL입니다.              |

## 문제 해결 / FAQ

<AccordionGroup>
  <Accordion title="응답 형태가 OpenAI 비디오 라우트와 다릅니다">
    Kling은 `data.task_id`, `data.task_status`, `data.task_result` 같은 provider별 JSON 필드를 사용합니다. OpenAI 호환 `/v1/videos` 라우트처럼 파싱하지 마세요.
  </Accordion>

  <Accordion title="작업이 succeed 상태에 도달하지 않습니다">
    제한된 폴링을 사용하고 작업이 실패하면 `data.task_status_msg`를 확인하세요. 나중에 진단할 수 있도록 task ID를 저장하세요.
  </Accordion>

  <Accordion title="callback_url과 폴링 중 무엇을 사용해야 하나요">
    기본 방식으로는 폴링을 사용하세요. 푸시 전달이 필요하면 `callback_url`을 추가한 뒤, 최종 상태는 폴링으로 정합성을 확인하세요.
  </Accordion>
</AccordionGroup>

## 다음 단계

* [Kling text-to-video API reference](/api/video/kling/text-to-video)를 읽어보세요.
* [Get a Kling task](/api/video/kling/individual-queries)로 폴링하세요.
* [Use Kling callback URLs](/api/video/kling/callback_url)로 callback을 설정하세요.
* [Models](/ko/overview/models)에서 Kling 비디오 모델을 찾아보세요.
* [Use polling and webhooks for video generation](/ko/guides/webhook-and-polling-for-video-generation)을 검토하세요.
* [Estimate request cost before calling a model](/ko/guides/how-to-estimate-cost-before-calling-a-model)로 작업 비용을 추정하세요.
