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

> 设置 webhooks 实时接收任务完成事件，减少轮询，为应用构建可靠的异步工作流。

## 概述

与其反复轮询 `GET /jobs/{id}`，你可以提供一个 webhook URL，让任务完成时收到 POST 请求。这更高效，并减少不必要的 API 调用。

## 使用 Webhooks

在任意生成请求中添加 `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>

## Webhook 载荷

任务完成时，你的 webhook 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 状态码。如果需要，可以异步处理 webhook 数据。
</Check>

<Warning>
  **验证载荷** - 在处理结果之前，先确认 `job_id` 对应的是你发起的任务。
</Warning>

* 出于安全考虑使用 HTTPS 端点
* 实现幂等，以防重复投递
* 记录 webhook 收到的日志以便调试

## Webhooks 与轮询

| 方式           | 优点            | 缺点            |
| ------------ | ------------- | ------------- |
| **Webhooks** | 实时通知，API 调用更少 | 需要公开可访问的端点    |
| **轮询**       | 任何地方都能用，无需服务器 | API 调用更多，略有延迟 |

如果你有可以接收 HTTP 请求的服务器，建议使用 webhooks。对于客户端应用或无法公开端点的场景，则使用轮询。

## 下一步

<CardGroup cols={2}>
  <Card title="任务生命周期" icon="cube" href="/developers/job-lifecycle">
    了解任务状态和状态轮询
  </Card>

  <Card title="代码示例" icon="code" href="/developers/examples/text-to-image">
    查看包含 webhook 处理的完整示例
  </Card>
</CardGroup>
