> ## 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 a signed POST request when a Krea API job finishes, verify its Ed25519 signature, and handle retries.

## Overview

Instead of polling `GET /jobs/{id}`, give Krea a webhook URL. Krea sends the job to that URL when it finishes.

## Using webhooks

Add the `X-Webhook-URL` header to any generation request. When the job completes, fails, or is cancelled, Krea sends a POST request to that URL.

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
// 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={"theme":{"light":"github-light-default","dark":"vesper"}}
curl -X POST https://api.krea.ai/generate/image/bfl/flux-1-dev \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -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={"theme":{"light":"github-light-default","dark":"vesper"}}
import os

import requests

API_BASE = "https://api.krea.ai"
API_TOKEN = os.environ["KREA_API_KEY"]

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={"theme":{"light":"github-light-default","dark":"vesper"}}
package main

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

func main() {
    apiBase := "https://api.krea.ai"
    apiToken := os.Getenv("KREA_API_KEY")

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

## Webhook payload

The request body has the same shape as the `GET /jobs/{id}` response:

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

## Verifying signatures

Krea signs every webhook with Ed25519. Verify the signature before you trust a payload, and reject requests that have no signature.

| Header | Value |
| - | - |
| `X-Krea-Webhook-Timestamp` | When Krea sent the request, in Unix seconds |
| `X-Krea-Webhook-Url` | The `X-Webhook-URL` you sent with the job |
| `X-Krea-Webhook-Metadata` | Reserved, currently empty |
| `X-Krea-Webhook-Signature` | Hex-encoded Ed25519 signature |

Krea signs the lowercase hex SHA-256 of the timestamp, URL, metadata, and raw request body, joined with newlines:

```text theme={"theme":{"light":"github-light-default","dark":"vesper"}}
hex(sha256(timestamp + "\n" + url + "\n" + metadata + "\n" + raw_body))
```

To verify a request:

1. Check that `X-Krea-Webhook-Url` exactly matches the `X-Webhook-URL` you sent with the job.
2. Check that the timestamp is within 5 minutes of your server's current time.
3. Accept the request if the signature verifies with any key in `https://api.krea.ai/.well-known/jwks.json`. Cache the keys for at most 24 hours. Krea publishes a new key 24 hours before it starts signing with it.

Hash the raw body bytes, not re-serialized JSON. For example, use `express.raw()` in Express, `await request.arrayBuffer()` in Fetch API frameworks, or `request.get_data()` in Flask. Treat a missing `X-Krea-Webhook-Metadata` header as an empty string.

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
import { createHash, createPublicKey, verify } from "node:crypto";

// The X-Webhook-URL you send with your jobs
const WEBHOOK_URL = "https://your-server.com/webhook";

let publicKeys = [];
let publicKeysFetchedAt = 0;

// headers is a Fetch API Headers object, rawBody is a Buffer
export async function verifyKreaWebhook(headers, rawBody) {
  const timestamp = headers.get("X-Krea-Webhook-Timestamp");
  const url = headers.get("X-Krea-Webhook-Url");
  const signature = headers.get("X-Krea-Webhook-Signature") ?? "";
  const metadata = headers.get("X-Krea-Webhook-Metadata") ?? "";

  if (url !== WEBHOOK_URL) return false;
  if (!(Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300)) return false;

  if (Date.now() - publicKeysFetchedAt > 60 * 60 * 1000) {
    const { keys } = await (await fetch("https://api.krea.ai/.well-known/jwks.json")).json();
    publicKeys = keys.map((jwk) => createPublicKey({ key: jwk, format: "jwk" }));
    publicKeysFetchedAt = Date.now();
  }

  const message = createHash("sha256")
    .update(`${timestamp}\n${url}\n${metadata}\n`)
    .update(rawBody)
    .digest("hex");

  return publicKeys.some((key) =>
    verify(null, Buffer.from(message), key, Buffer.from(signature, "hex"))
  );
}
```

```python Python theme={"theme":{"light":"github-light-default","dark":"vesper"}}
import base64
import hashlib
import time

import requests
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

# The X-Webhook-URL you send with your jobs
WEBHOOK_URL = "https://your-server.com/webhook"

_public_keys = []
_public_keys_fetched_at = 0.0


# headers is a case-insensitive mapping, such as Flask's request.headers
def verify_krea_webhook(headers, raw_body: bytes) -> bool:
    global _public_keys, _public_keys_fetched_at
    timestamp = headers.get("X-Krea-Webhook-Timestamp", "")
    url = headers.get("X-Krea-Webhook-Url")
    metadata = headers.get("X-Krea-Webhook-Metadata", "")

    try:
        if url != WEBHOOK_URL or abs(time.time() - int(timestamp)) > 300:
            return False
        signature = bytes.fromhex(headers.get("X-Krea-Webhook-Signature", ""))
    except ValueError:
        return False

    if time.time() - _public_keys_fetched_at > 3600:
        jwks = requests.get("https://api.krea.ai/.well-known/jwks.json", timeout=10).json()
        _public_keys = [
            Ed25519PublicKey.from_public_bytes(base64.urlsafe_b64decode(jwk["x"] + "="))
            for jwk in jwks["keys"]
        ]
        _public_keys_fetched_at = time.time()

    signed = f"{timestamp}\n{url}\n{metadata}\n".encode() + raw_body
    message = hashlib.sha256(signed).hexdigest().encode()
    for key in _public_keys:
        try:
            key.verify(signature, message)
            return True
        except InvalidSignature:
            pass

    return False
```

## Delivery and retries

Return a `2xx` within 15 seconds. If the request times out, can't connect, or gets a `5xx`, `408`, `423`, `425`, or `429`, Krea retries for about 10 minutes with a new timestamp and signature each time. Krea doesn't retry any other `4xx`.

The same job can arrive more than once, so deduplicate on `job_id` and `status`.

## Webhooks vs. polling

| Approach | Pros | Cons |
| - | - | - |
| **Webhooks** | Results arrive as soon as the job finishes, with fewer API calls | Requires a public endpoint |
| **Polling** | Works anywhere, no server needed | More API calls, and results arrive up to one poll interval late |

Use webhooks when you have a server that can receive HTTP requests. Use polling for client-side apps or when you can't expose a public endpoint.

## Next steps

> [card] [Job Lifecycle](https://www.krea.ai/docs/developers/job-lifecycle.md)
>
> Learn about job states and status polling

> [card] [Code Examples](https://www.krea.ai/docs/developers/examples/text-to-image.md)
>
> Generate an image with the API, end to end


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.