# Webhooks

Webhooks send a signed HTTPS `POST` to your server when a threshold rule of your organization fires. Use them to respond to a custom alert rule without polling the API.

Precip webhooks follow the [Standard Webhooks](https://www.standardwebhooks.com/) spec, so you can verify them with the official libraries.

:::note
Webhooks and API-managed alert rules are included on **Growth** ($500/mo) and **Enterprise** API plans, and available on **Starter + Webhooks** ($150/mo). [View plans & subscribe →](/pricing). Free and personal (hobby) keys receive `403 commercial_tier_required`, and Starter keys without webhooks receive `403 webhooks_plan_required`.
:::

## What fires and when

You can create threshold alert rules via `POST /api/v1/alert-rules` (or the `create_alert_rule` MCP tool) as well as in the [Precip app](https://app.precip.ai) — for example "more than 25.4 mm of rain in 24 hours" or "wind above 15 m/s in the forecast". When a rule fires, Precip sends one `threshold_rule.triggered` event to each of your endpoints that listens to that rule. The event lists each location where the value crossed the threshold.

- Webhooks and alert rules belong to an organization. Only admins of the organization can manage them. If you are on a paid API plan and do not yet belong to an organization, Precip automatically creates a default organization for you and migrates any personal saved locations into it. When you belong to one organization, `orgId` is optional on all location, alert rule, and webhook requests.
- Each endpoint gets at most one event per rule in each cooldown period. The cooldown follows the `frequency` of the rule (`hourly`, `daily`, or `weekly`).
- An organization can have 10 endpoints (5 alert rules on Starter + Webhooks, 10 on Growth, and up to 1,000 on Enterprise).

### Delivery channels & recipients

- **API-created alert rules (`POST /api/v1/alert-rules`):** Created as **webhook-only** (`delivery_medium: "webhook"`). They do not send mobile push notifications or emails by default. When a rule fires, Precip delivers a signed `threshold_rule.triggered` POST to **every enabled webhook endpoint on the same organization** that subscribes to `threshold_rule.triggered` and either has `ruleIds: null` (all organization rules, the default) or includes that rule's `id` in `ruleIds`.
- **Adding push or email in the Precip app:** API-created alert rules also appear in **Settings → Notifications** in the [Precip app](https://app.precip.ai) with a **Webhook** badge. Organization admins can optionally add **Push** and/or **Email** channels there to notify specific team members (or all organization members) in addition to the webhook delivery.
- **App-created alert rules:** Rules created in the Precip app keep their push notifications and emails unchanged, and also trigger matching organization webhook endpoints as an additional channel.

```bash
curl -X POST 'https://api.precip.ai/api/v1/alert-rules' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "Heavy 24h rainfall",
    "alert_type": "precipitation",
    "direction": "above",
    "threshold_mm": 25.4,
    "window_hours": 24,
    "frequency": "hourly",
    "scope": "all_locations"
  }'
```

To route a rule to only one webhook endpoint (instead of every endpoint on the organization), pass the returned rule `id` in `ruleIds` when creating or updating that endpoint via `POST /api/v1/webhooks` or `PATCH /api/v1/webhooks/:id`.

## Create an endpoint

Send your API key as `Authorization: Bearer YOUR_API_KEY`, as for all other requests. Copy your key from [API Keys & Subscriptions](/subscriptions) (for self-serve Starter + Webhooks and Growth plans) or from **Settings → API & AI assistants** in the Precip app (for Enterprise account keys). The key must belong to an admin of the organization.

```bash
curl -X POST 'https://api.precip.ai/api/v1/webhooks' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com/precip/webhooks",
    "description": "Irrigation scheduler"
  }'
```

The response has the endpoint and its signing secret:

```json
{
  "endpoint": {
    "id": "Xk3T9pQ2LmN8vR4sW7yZa1",
    "orgId": "R7cP2mQ9sL4vN8xK3tW6yB",
    "url": "https://example.com/precip/webhooks",
    "description": "Irrigation scheduler",
    "events": ["threshold_rule.triggered"],
    "ruleIds": null,
    "enabled": true,
    "disabledReason": null,
    "disabledAt": null,
    "lastSuccessAt": null,
    "lastFailureAt": null,
    "createdAt": "2026-11-01T09:30:00.000Z",
    "updatedAt": "2026-11-01T09:30:00.000Z"
  },
  "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
}
```

The times in API responses are UTC with milliseconds, for example `2026-11-01T09:30:00.000Z`. The times in an event body have no milliseconds. Use an ISO 8601 parser for both.

| Field | Notes |
| --- | --- |
| `url` | Required. See [URL rules](#url-rules). |
| `description` | A note for you, up to 200 characters. |
| `events` | Leave it out to get `threshold_rule.triggered`. |
| `ruleIds` | Only send events for these rules (1 to 200 IDs). Leave it out, or send `null`, to get every rule of the organization. An empty list is not valid. |
| `orgId` | Which organization. Leave it out when you are an admin of only one organization or when using an organization-scoped commercial API key. |

If you are an admin of more than one organization and using a user-scoped commercial key, pass `orgId` (`400 org_required` otherwise). Organization-scoped commercial keys are bound to their organization automatically (passing a different `orgId` returns `403 org_key_mismatch`). Call `GET /api/v1/account` or `GET /api/v1/orgs` (see the [API reference](/api)) to list your organizations and their IDs.

See the [API reference](/api) for all webhook requests: list, get, update, delete, rotate the secret, send a test event, and list deliveries.

## The signing secret

The secret is shown **only once**: in the response of the create request and of the rotate request. Store it in your secret manager. List and get never return it.

To change the secret, rotate it:

```bash
curl -X POST 'https://api.precip.ai/api/v1/webhooks/ENDPOINT_ID/rotate-secret' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

The response has the new secret. For the next 24 hours, the old secret stays valid: each delivery has two signatures, one from the new secret and one from the old secret. Put the new secret on your server within these 24 hours. After that, only the new secret signs.

Only the secret just before the latest rotation stays valid. If you rotate again within the 24 hours, the older secret stops at once. So if you lose the response of a rotation, put the secret of the next rotation on your server at once.

## The request

Each delivery is a `POST` with a JSON body and these headers:

| Header | Value |
| --- | --- |
| `content-type` | `application/json` |
| `user-agent` | `Precip-Webhooks/1.0` |
| `webhook-id` | The delivery ID, for example `msg_Fp4Rk8Wz2Ns6Qt9Lm3Xv5H`. It is the same on each retry. |
| `webhook-timestamp` | The time of this attempt, in Unix seconds. |
| `webhook-signature` | One or more signatures, separated by a space: `v1,<base64>`. There are two during a rotation. |

### `threshold_rule.triggered`

```json
{
  "type": "threshold_rule.triggered",
  "timestamp": "2026-11-18T14:15:00Z",
  "data": {
    "rule": {
      "id": "H2kL9mP4qR7sT1vW5xZ8aC",
      "org_id": "R7cP2mQ9sL4vN8xK3tW6yB",
      "alert_type": "precipitation",
      "observation_type": "observation",
      "direction": "above",
      "threshold": 25.4,
      "unit": "mm",
      "window_hours": 24,
      "forecast_probability_pct": null
    },
    "window": {
      "start": "2026-11-17T14:00:00Z",
      "end": "2026-11-18T14:00:00Z"
    },
    "locations": [
      {
        "id": "Lq8Wn3Zp6Tr1Ky4Mb7Vc2D",
        "name": "North field",
        "latitude": 41.6,
        "longitude": -93.6,
        "value": 31.2,
        "unit": "mm"
      }
    ]
  }
}
```

| Field | Notes |
| --- | --- |
| `timestamp` | When the rule fired (UTC). |
| `rule.alert_type` | `precipitation`, `wind`, or `temperature`. |
| `rule.observation_type` | `observation` (what fell or was measured) or `forecast`. |
| `rule.direction` | `above` or `below` the threshold. |
| `rule.threshold`, `rule.unit` | The threshold of the rule. |
| `rule.window_hours` | The length of the window of the rule. |
| `rule.forecast_probability_pct` | The minimum chance (0–100) for a precipitation forecast rule, else `null`. |
| `window` | The hours that Precip checked, rounded to the hour. For observations, the last `window_hours` hours. For forecasts, the next `window_hours` hours. |
| `locations` | Each location where the value crossed the threshold, with the value in that window. |

Units are always metric, whatever your app settings: `mm` for precipitation, `m/s` for wind, and `C` for temperature.

### `webhook.test`

Sent by [Send a Test Event](#test-and-the-delivery-log):

```json
{
  "type": "webhook.test",
  "timestamp": "2026-11-18T15:02:00Z",
  "data": {
    "endpoint_id": "Xk3T9pQ2LmN8vR4sW7yZa1",
    "message": "Test event from Precip"
  }
}
```

Ignore event types that you don't know. Precip can add types and fields later.

## Verify the signature

Always verify the signature before you use an event. Use the **raw body** as you received it. If you parse the JSON and serialize it again, the bytes change and the signature fails.

### With the Standard Webhooks library (recommended)

JavaScript (`npm install standardwebhooks`), with Express:

```js
import express from "express";
import { Webhook } from "standardwebhooks";

const wh = new Webhook(process.env.PRECIP_WEBHOOK_SECRET); // "whsec_..."
const app = express();

app.post(
  "/precip/webhooks",
  express.raw({ type: "application/json" }),
  (req, res) => {
    let event;
    try {
      event = wh.verify(req.body, req.headers);
    } catch (err) {
      return res.status(400).send("Bad signature");
    }
    // Answer fast, then do the work in the background.
    res.status(204).end();
    handleEvent(req.headers["webhook-id"], event);
  }
);
```

Python (`pip install standardwebhooks`), with Flask:

```python
import os

from flask import Flask, request
from standardwebhooks import Webhook, WebhookVerificationError

wh = Webhook(os.environ["PRECIP_WEBHOOK_SECRET"])  # "whsec_..."
app = Flask(__name__)


@app.post("/precip/webhooks")
def precip_webhook():
    try:
        event = wh.verify(request.get_data(), dict(request.headers))
    except WebhookVerificationError:
        return "Bad signature", 400
    handle_event(request.headers["webhook-id"], event)
    return "", 204
```

The libraries check the timestamp (5 minutes), compare in constant time, and accept any of the signatures in the header.

### Without a library

The signature is an HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{raw body}`. The key is the part of the secret after `whsec_`, decoded from base64. To verify:

1. Reject the request if the timestamp is more than 5 minutes from your clock. This stops replays.
2. Compute the signature and encode it in base64.
3. Split `webhook-signature` at each space. Accept the request if any `v1,` entry is equal to your signature. Compare in constant time.

Node:

```js
import crypto from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

// rawBody is the body as a Buffer or string, before any JSON parse.
export function verifyPrecipWebhook(secret, headers, rawBody) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) throw new Error("Missing headers");

  const sentAt = Number(timestamp);
  const now = Math.floor(Date.now() / 1000);
  if (!Number.isInteger(sentAt) || Math.abs(now - sentAt) > TOLERANCE_SECONDS) {
    throw new Error("Timestamp too old or too new");
  }

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = crypto
    .createHmac("sha256", key)
    .update(`${id}.${timestamp}.`)
    .update(rawBody)
    .digest();

  const valid = signatures.split(" ").some((entry) => {
    const [version, signature] = entry.split(",");
    if (version !== "v1" || !signature) return false;
    const given = Buffer.from(signature, "base64");
    return given.length === expected.length && crypto.timingSafeEqual(given, expected);
  });
  if (!valid) throw new Error("No valid signature");
  return JSON.parse(rawBody);
}
```

Python:

```python
import base64
import hashlib
import hmac
import json
import time

TOLERANCE_SECONDS = 5 * 60


def verify_precip_webhook(secret: str, headers: dict, raw_body: bytes) -> dict:
    """raw_body is the body as bytes, before any JSON parse."""
    headers = {k.lower(): v for k, v in headers.items()}
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not (msg_id and timestamp and signatures):
        raise ValueError("Missing headers")

    try:
        sent_at = int(timestamp)
    except ValueError:
        raise ValueError("Bad timestamp")
    if abs(time.time() - sent_at) > TOLERANCE_SECONDS:
        raise ValueError("Timestamp too old or too new")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest())

    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature.encode(), expected):
            return json.loads(raw_body)
    raise ValueError("No valid signature")
```

## Respond and retry

Return a `2xx` status within 10 seconds. Do the work after you respond, for example in a queue. Precip reads only the first 1 KB of your response and doesn't follow redirects.

| Your response | What Precip does |
| --- | --- |
| `2xx` | Success. |
| `408`, `429`, `5xx`, a timeout, or a connection or TLS error | Retry. |
| `3xx` or another `4xx` | Failure. No retry. |

Precip makes up to 8 attempts. The wait after each failed attempt:

| After attempt | Wait |
| --- | --- |
| 1 | 1 minute |
| 2 | 5 minutes |
| 3 | 30 minutes |
| 4 | 2 hours |
| 5 | 5 hours |
| 6 | 10 hours |
| 7 | 10 hours |

After the 8th failed attempt (about 28 hours after the first), the delivery has the status `failed`.

### Skip duplicates

A retry can come after your server already handled the event, for example when your response was too slow. Each attempt of a delivery has the same `webhook-id`. Save the IDs that you handled, and skip an event with an ID that you already saw. Keep the IDs for at least 2 days.

### Endpoints that fail are turned off

When 3 deliveries in a row end as `failed`, Precip turns the endpoint off (`enabled: false`, `disabledReason: "failing"`) and sends an email to the admins of the organization. A success resets the count. While an endpoint is off, Precip sends it no events, and events of that time are not sent later.

Repair your server, then turn the endpoint on again. Then send a [test event](#test-and-the-delivery-log) to check it:

```bash
curl -X PATCH 'https://api.precip.ai/api/v1/webhooks/ENDPOINT_ID' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{"enabled": true}'
```

This also clears `disabledReason` and the failure count. You can turn an endpoint off yourself with `{"enabled": false}`.

## Test and the delivery log

Send a `webhook.test` event to check your server:

```bash
curl -X POST 'https://api.precip.ai/api/v1/webhooks/ENDPOINT_ID/test' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

The response is `202` with the `deliveryId`. The event is signed and retried like a real event, and is usually sent within a minute.

Precip sends a test event only while the endpoint is on. On an endpoint that is off, the test delivery ends as `failed` with the error `endpoint disabled`, and no request goes to your server. After a repair, turn the endpoint on first, then send the test.

The delivery log shows the last deliveries, newest first, with the payload, the number of attempts, the last status code, the error, and the first 1 KB of your response:

```bash
curl 'https://api.precip.ai/api/v1/webhooks/ENDPOINT_ID/deliveries?limit=20&status=failed' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

`limit` is 1 to 100 (default 20). `status` is `pending`, `succeeded`, or `failed`. Precip keeps deliveries for 30 days. You can't send a delivery again from the log.

## URL rules

Precip checks the URL when you create or change an endpoint, and again before each attempt.

- Use `https://`. Precip checks the TLS certificate of your host.
- Use a public host. Precip refuses `localhost`, names that end in `.local`, `.internal`, or `.localhost`, and private, loopback, link-local, and other non-public IP addresses (IPv4 and IPv6). Each address that your host name resolves to must be public.
- Don't put a user name or password in the URL. To identify Precip, verify the signature.
- Up to 2,048 characters.
- Precip doesn't follow redirects. A `3xx` response is a failure.

If your DNS points to a non-public address at the time of an attempt, Precip retries that attempt.

## Errors

The error body has an `error` message and a `code`.

| Status | `code` | Meaning |
| --- | --- | --- |
| 400 | `invalid_webhook` | A field or query value is not valid. The message tells which. |
| 400 | `org_required` | `orgId` is missing, and you are an admin of more than one organization, or of none. Pass `orgId`. If you are not an admin of that organization, you then get `403 webhook_forbidden`. |
| 400 | `invalid_rule_ids` | A rule ID in `ruleIds` is not a rule of the organization. |
| 403 | `commercial_tier_required` | Your API key doesn't have commercial access. The body has an `upgradeUrl`. |
| 403 | `webhooks_plan_required` | Your Starter plan does not include webhooks. Upgrade to Starter + Webhooks, Growth, or Enterprise. |
| 403 | `org_required` | You are not in an organization. |
| 403 | `org_key_mismatch` | The API key is scoped to a different organization than `orgId`. |
| 403 | `webhook_forbidden` | You are not an admin of the organization. |
| 403 | `account_required` | The key isn't tied to a Precip user or organization. |
| 404 | `webhook_not_found` | No endpoint with this ID in your organizations. |
| 409 | `webhook_limit_reached` | The organization has 10 endpoints. Delete one to add another. |
| 409 | `webhook_secret_conflict` | Another rotation changed the secret while this call ran. Use the secret from that call, or rotate again. |
| 503 | `webhooks_unavailable` | Webhooks are not available right now. Try again later. |

Webhook requests count toward a limit of 30 requests a minute per account (`429` with a `Retry-After` header).

## Need help?

Contact [support@getprecip.com](mailto:support@getprecip.com).
