> ## Documentation Index
> Fetch the complete documentation index at: https://www.krea.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

> 웹훅을 설정해 실시간 작업 완료 이벤트를 수신하고, 폴링을 줄이며, 애플리케이션에서 안정적인 비동기 워크플로우를 구축하세요.

## 개요

`GET /jobs/{id}`를 반복해서 폴링하는 대신, 작업이 완료될 때 POST 요청을 받을 웹훅 URL을 제공할 수 있습니다. 이는 더 효율적이며 불필요한 API 호출을 줄여줍니다.

## 웹훅 사용하기

어떤 생성 요청에든 `X-Webhook-URL` 헤더를 추가하세요. 작업이 종료 상태(completed, failed, cancelled)에 도달하면 API가 제공한 URL로 전체 작업 데이터를 담아 POST 요청을 보냅니다.

<CodeGroup>
  ```javascript Node.js theme={null}
  // npm install @krea-ai/sdk
  import { Krea } from "@krea-ai/sdk";

  const krea = new Krea({ apiKey: process.env.KREA_API_KEY });

  const job = await krea.image(
    "bfl/flux-1-dev",
    {
      prompt: "a serene mountain landscape at sunset",
      width: 1024,
      height: 576
    },
    { webhookUrl: "https://your-server.com/webhook" }
  );

  console.log(`Job ID: ${job.job_id}`);
  // Your webhook will receive the results when complete
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.krea.ai/generate/image/bfl/flux-1-dev \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json" \
    -H "X-Webhook-URL: https://your-server.com/webhook" \
    -d '{
      "prompt": "a serene mountain landscape at sunset",
      "width": 1024,
      "height": 576
    }'
  ```

  ```python Python theme={null}
  import requests

  API_BASE = "https://api.krea.ai"
  API_TOKEN = "your-token-secret"

  response = requests.post(
      f"{API_BASE}/generate/image/bfl/flux-1-dev",
      headers={
          "Authorization": f"Bearer {API_TOKEN}",
          "Content-Type": "application/json",
          "X-Webhook-URL": "https://your-server.com/webhook"
      },
      json={
          "prompt": "a serene mountain landscape at sunset",
          "width": 1024,
          "height": 576
      }
  )

  job = response.json()
  print(f"Job ID: {job['job_id']}")
  # Your webhook will receive the results when complete
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "net/http"
  )

  func main() {
      apiBase := "https://api.krea.ai"
      apiToken := "your-token-secret"

      payload := map[string]interface{}{
          "prompt": "a serene mountain landscape at sunset",
          "width":  1024,
          "height": 576,
      }

      jsonData, _ := json.Marshal(payload)
      req, _ := http.NewRequest("POST", apiBase+"/generate/image/bfl/flux-1-dev", bytes.NewBuffer(jsonData))
      req.Header.Set("Authorization", "Bearer "+apiToken)
      req.Header.Set("Content-Type", "application/json")
      req.Header.Set("X-Webhook-URL", "https://your-server.com/webhook")

      client := &http.Client{}
      resp, _ := client.Do(req)
      defer resp.Body.Close()

      var job map[string]interface{}
      json.NewDecoder(resp.Body).Decode(&job)
      fmt.Printf("Job ID: %s\n", job["job_id"])
      // Your webhook will receive the results when complete
  }
  ```
</CodeGroup>

## 웹훅 페이로드

작업이 완료되면 웹훅 URL은 다음과 같은 작업 데이터가 담긴 POST 요청을 받습니다:

```json theme={null}
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "created_at": "2025-01-15T10:30:00.000Z",
  "completed_at": "2025-01-15T10:30:05.000Z",
  "result": {
    "urls": ["https://..."]
  }
}
```

## 모범 사례

<Check>
  **빠르게 응답하세요** - 2xx 상태 코드를 신속하게 반환하세요. 필요하다면 웹훅 데이터는 비동기로 처리하세요.
</Check>

<Warning>
  **페이로드를 검증하세요** - 결과를 처리하기 전에 `job_id`가 여러분이 시작한 작업과 일치하는지 확인하세요.
</Warning>

* 보안을 위해 HTTPS 엔드포인트를 사용하세요
* 중복 전달에 대비해 멱등성을 구현하세요
* 디버깅을 위해 웹훅 수신 로그를 남기세요

## 웹훅 대 폴링

| 방식     | 장점                | 단점                |
| ------ | ----------------- | ----------------- |
| **웹훅** | 실시간 알림, 적은 API 호출 | 공개 엔드포인트 필요       |
| **폴링** | 어디서나 동작, 서버 불필요   | API 호출 증가, 약간의 지연 |

HTTP 요청을 받을 수 있는 서버가 있다면 웹훅을 사용하세요. 클라이언트 측 애플리케이션이거나 공개 엔드포인트를 노출할 수 없다면 폴링을 사용하세요.

## 다음 단계

<CardGroup cols={2}>
  <Card title="Job Lifecycle" icon="cube" href="/developers/job-lifecycle">
    작업 상태와 상태 폴링에 대해 알아보기
  </Card>

  <Card title="Code Examples" icon="code" href="/developers/examples/text-to-image">
    웹훅 처리가 포함된 전체 예제 보기
  </Card>
</CardGroup>
