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

> Siapkan webhooks untuk menerima event penyelesaian job secara real-time, mengurangi polling, dan membangun alur kerja asinkron yang andal di aplikasi Anda.

## Ikhtisar

Alih-alih melakukan polling `GET /jobs/{id}` berulang kali, Anda dapat menyediakan URL webhook untuk menerima POST request saat job Anda selesai. Ini lebih efisien dan mengurangi panggilan API yang tidak perlu.

## Menggunakan Webhooks

Tambahkan header `X-Webhook-URL` ke request generasi mana pun. Ketika job mencapai status terminal (completed, failed, atau cancelled), API akan mengirim POST request ke URL Anda dengan data job lengkap.

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

## Payload Webhook

Ketika job selesai, URL webhook Anda menerima POST request dengan data job:

```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://..."]
  }
}
```

## Praktik Terbaik

<Check>
  **Merespons dengan cepat** - Kembalikan status code 2xx sesegera mungkin. Proses data webhook secara asinkron bila perlu.
</Check>

<Warning>
  **Validasi payload** - Verifikasi `job_id` sesuai dengan job yang Anda mulai sebelum memproses hasil.
</Warning>

* Gunakan endpoint HTTPS untuk keamanan
* Terapkan idempotensi untuk menangani pengiriman ganda
* Log penerimaan webhook untuk debugging

## Webhooks vs Polling

| Pendekatan   | Kelebihan                                         | Kekurangan                                    |
| ------------ | ------------------------------------------------- | --------------------------------------------- |
| **Webhooks** | Notifikasi real-time, panggilan API lebih sedikit | Membutuhkan endpoint publik                   |
| **Polling**  | Bekerja di mana saja, tidak perlu server          | Lebih banyak panggilan API, ada sedikit delay |

Gunakan webhooks bila Anda memiliki server yang dapat menerima HTTP request. Gunakan polling untuk aplikasi sisi klien atau ketika Anda tidak dapat mengekspos endpoint publik.

## Langkah Berikutnya

<CardGroup cols={2}>
  <Card title="Job Lifecycle" icon="cube" href="/developers/job-lifecycle">
    Pelajari status job dan polling status
  </Card>

  <Card title="Contoh Kode" icon="code" href="/developers/examples/text-to-image">
    Lihat contoh lengkap dengan penanganan webhook
  </Card>
</CardGroup>
