# Webhooks

## Advanced: Webhooks

Webhooks provide a robust mechanism for receiving real-time updates about asynchronous operations (like model training, image/video generation) without resorting to inefficient polling.

### Overview

1. **Configure Endpoint:** Provide a secure HTTPS URL in your REALM AI account settings where you can receive POST requests.
2. **Receive Events:** When a job you initiated changes state (e.g., `processing` -> `completed`, `queued` -> `failed`), REALM AI sends a JSON payload to your configured URL.
3. **Verify Signature:** (Recommended) Each webhook request should include a signature in its headers (e.g., `X-Webhook-Signature`). You can verify this signature using a shared secret (provided in your account settings) to ensure the request originated from REALM AI.
4. **Process Payload:** Extract information like `jobId`, `status`, `results` (if completed), or `errorCode` (if failed) from the JSON payload and update your application state accordingly.
5. **Respond Quickly:** Acknowledge receipt of the webhook immediately with a `2xx` status code (e.g., `200 OK` or `202 Accepted`). Perform time-consuming processing asynchronously to avoid timeouts.

### Payload Structure (Example - Job Completion)

```json
{
  "eventId": "evt_webhook_12345",
  "eventType": "job.completed", // e.g., job.processing, job.failed, model.training.completed
  "apiVersion": "v1",
  "createdAt": "2024-03-10T15:06:15Z",
  "data": {
    "object": "job",
    "jobId": "job_img_gen_123",
    "jobType": "image_generation",
    "status": "completed",
    "results": [
      {
        "imageId": "img_abc",
        "url": "https://cdn.realm.ai/images/img_abc.png",
        "seed": 123456789
      }
    ],
    "completedAt": "2024-03-10T15:06:10Z"
    // ... other relevant job metadata
  }
}
```

### Best Practices

* **Security:** Always use HTTPS for your endpoint and verify webhook signatures.
* **Idempotency:** Handle potential duplicate webhook deliveries gracefully (e.g., using the `eventId`).
* **Error Handling:** Implement robust error handling and logging for webhook processing.
* **Responsiveness:** Respond to webhooks within a few seconds to avoid retries from REALM AI.

*(Detailed configuration steps and signature verification examples will be provided here.)*
