# Schedules, triggers and webhooks

> Run on a schedule, react to events, receive webhooks and send signed deliveries.

Source: https://usewrit.app/docs/automations-webhooks/

Your APIs don't have to wait for a call. They can run on a schedule, start when something happens
(a page changes, another run finishes, an outside system sends a webhook), and tell other systems
what they found. Simple cases live on an API's **Call** tab; anything with several
steps is an automation.

## Run an API on a schedule

-

1. **Open the triggers**

Open the API under **APIs**, go to its **Call** tab and find **Triggers**.

-

2. **Pick when it runs**

Click **Schedule this** and choose **Interval** (every 5 minutes up to every 24 hours), **Daily** or **Weekly**. Daily and weekly runs take a
time (**At**) and the days of the week, in the time zone shown under the picker.

-

3. **Turn it on**

Click **Enable Schedule**. On an API with several functions, the schedule calls the
functions you chose and whatever they need first, such as the sign-in. **Turn off** pauses it.

In the same **Triggers** list, **Run when a page changes** picks one of
your monitors: the API runs each time that monitor detects a change.

An AI assistant connected to Writ sets the same schedules with the `writ_set_schedule` tool: `every_minutes` for an interval, or `kind` `daily`/`weekly` with `time` (HH:MM), `days` (1 = Monday to 7 = Sunday) and `tz`. It can also limit the schedule to some `functions` and save `inputs` for them.

```json
// Every hour
{ "workflow_id": 42, "every_minutes": 60 }

// Monday, Wednesday and Friday at 08:30, Montreal time, one function only
{
  "workflow_id": 42,
  "kind": "weekly",
  "time": "08:30",
  "days": [1, 3, 5],
  "tz": "America/Toronto",
  "functions": ["top_stories"],
  "inputs": { "limit": 10 }
}
```

> **cost:** Each scheduled run on Writ Cloud costs the same as a call: 2 credits without a browser, 20 with one. When the API runs on your linked computer (the schedule says runs on your device), scheduled runs are free. Schedules are intervals, daily or weekly times; cron expressions are not supported.

## Build an automation

An automation is a trigger followed by steps. Open **Automations** and click **New Automation**, or describe what you want in the bar at the top ("Describe what
you want to automate — AI will build it.") and review the blocks it adds. **Test trigger** checks whether the trigger would fire on a sample, without running anything. Writ also
creates automations for you when you set up a reaction on a monitor or a workflow.

### Triggers

| Trigger | Starts the automation when |
| --- | --- |
| Content Change | A monitor detects a change on its page or selector. |
| Monitor Down, Monitor Stale, Monitor Recovered | A monitor can't reach its page, stops updating on time, or is healthy again. |
| Webhook Received | An outside system posts to the automation's URL (see below). |
| Schedule | An interval passes (1 minute or more), or a daily or weekly time comes. |
| Workflow Started, Workflow Completed | A chosen API starts, or finishes with success or an error. |
| AI Session Started, AI Session Completed | An AI browser session starts or finishes. |
| Crawl Started, Crawl Finished, Crawl Failed | A harvest starts, collects every page, or fails. |
| Streaming Session Started, Streaming Session Ended Desktop | A live session starts or ends. |
| Data Extracted Desktop | A run produces new rows. |
| File Received Desktop | A file is uploaded or arrives. |

### Steps

| Step | What it does |
| --- | --- |
| Condition | Continues only when a field matches a rule (equals, contains, greater than, matches a pattern and more). |
| For Each | Runs the steps below it once per item of a list. |
| Run Workflow | Runs one of your APIs or workflows. |
| Return Data | Sends data back to whoever called the webhook. |
| Send Notification | Alerts people or systems. See Alerts and notifications. |
| Run AI Agent | Gives an AI browser agent a task. |
| Create Persona | Saves a workflow's login as a persona. |
| Crawl Site, Scrape Pages | Harvests a site, or reads up to 5 pages right away. |
| Extract Data | Pulls named fields out of a page, a JSON value or text. |
| Append to Data | Copies matching rows from one dataset into another. |
| Start Streaming Session, Stop Streaming Session Desktop | Opens or closes a live session. |
| Save Data to File, Query & Export Data, Send File Desktop | Exports rows to a file, or delivers a file to a connector or webhook. |

Each step can use what earlier steps produced through placeholders such as `{{payload.field}}` or `{{result.field}}`. The builder lists the ones
available under **Available Placeholders**. An AI assistant can create automations
with the `writ_create_automation` tool.

## Receive webhooks

An incoming webhook gives an outside system (a shop, a form, Zapier, your own code) a URL that
starts an automation. Anything it sends as JSON becomes available to the steps as `{{payload.field}}`.

-

4. **Add the trigger**

In a new automation, pick the **Webhook Received** trigger, add your steps, and save.

-

5. **Copy the URL and the secret**

The trigger now shows **Your webhook URL** and a **Signing secret**.
Copy the secret at once: it is stored encrypted and never shown again. **Set a new signing secret** replaces it, and requests signed with the old one are refused from then on.

-

6. **Sign each request**

The sender signs every request with the secret, as shown below. The trigger also has a ready-made **Try it — example request**.

All your incoming webhooks are listed in **Developers → Endpoints → Incoming webhooks**, with the automation each one runs and its recent deliveries.

POST `https://api.usewrit.app/api/webhooks/hook/{token}` signature

- `X-Writ-Timestamp`: the current time in Unix seconds. Requests more than 5 minutes off are refused.
- `X-Writ-Signature`: `sha256=` followed by the hex HMAC-SHA256 of `timestamp + "." + body`, keyed with the secret. A GitHub-style `X-Hub-Signature-256` header is accepted too.
- Each signature is accepted once. Sending the exact same request again is refused with `403`; a missing or wrong signature gets `401`.

```bash
BODY='{"order_id": "A-1042", "total": 129.5}'
TS=$(date +%s)
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$WRIT_WEBHOOK_SECRET" | sed 's/^.* //')

curl -X POST "https://api.usewrit.app/api/webhooks/hook/Jx4mT9qLs2VbN7cR1dKe8wYh3pZaFu6G?wait=true" \
  -H "Content-Type: application/json" \
  -H "X-Writ-Timestamp: $TS" \
  -H "X-Writ-Signature: sha256=$SIG" \
  -d "$BODY"
```

```python
import hashlib, hmac, json, os, time, requests

url = "https://api.usewrit.app/api/webhooks/hook/Jx4mT9qLs2VbN7cR1dKe8wYh3pZaFu6G"
secret = os.environ["WRIT_WEBHOOK_SECRET"]

body = json.dumps({"order_id": "A-1042", "total": 129.5}).encode()
ts = str(int(time.time()))
sig = hmac.new(secret.encode(), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()

res = requests.post(
    url,
    params={"wait": "true"},   # optional: wait for the result
    data=body,                 # send the exact bytes you signed
    headers={
        "Content-Type": "application/json",
        "X-Writ-Timestamp": ts,
        "X-Writ-Signature": f"sha256={sig}",
    },
    timeout=130,
)
print(res.json())
```

```typescript
import { createHmac } from "node:crypto";

const url = "https://api.usewrit.app/api/webhooks/hook/Jx4mT9qLs2VbN7cR1dKe8wYh3pZaFu6G";
const secret = process.env.WRIT_WEBHOOK_SECRET!;

const body = JSON.stringify({ order_id: "A-1042", total: 129.5 });
const ts = Math.floor(Date.now() / 1000).toString();
const sig = createHmac("sha256", secret).update(`${ts}.${body}`).digest("hex");

const res = await fetch(`${url}?wait=true`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-Writ-Timestamp": ts,
    "X-Writ-Signature": `sha256=${sig}`,
  },
  body, // send the exact string you signed
});
console.log(await res.json());
```

Without `?wait=true`, the request returns at once and the automation runs in the
background. With it, the request stays open until the workflows the automation runs have finished
(up to 2 minutes; `&timeout=` sets 10 to 300 seconds) and returns what they collected,
or what a **Return Data** step sent back.

```json
{
  "success": true,
  "triggered": true,
  "status": "success",
  "extracted_data": { "price": 129.5, "in_stock": true },
  "runs": [
    {
      "task_id": 91834,
      "workflow_id": 42,
      "status": "success",
      "success": true,
      "extracted_data": { "price": 129.5, "in_stock": true },
      "error": null,
      "duration_ms": 4180
    }
  ]
}
```

> **limit:** Each webhook URL accepts 30 requests per minute, within your plan's calls per minute. Runs it starts cost the same credits as any other run.

### Call it with an API key instead

If the sender can't compute a signature, give the trigger a **Friendly URL (optional)**,
such as `new-order`. It is then also reachable at `https://api.usewrit.app/api/v1/webhooks/new-order` with `Authorization: Bearer wt_...` instead of a signature. The key needs permission to run triggers or workflows, and the friendly
URL counts as a published endpoint on your plan.

## Send signed webhooks

To tell another system what happened, add a **Send Notification** step on the **Outbound webhook** channel, either with a **Webhook URL** or with
webhook destinations you saved. Writ sends a JSON `POST` with these headers:

```http
POST /your/webhook HTTP/1.1
Content-Type: application/json
User-Agent: Writ-Webhook/1.0
X-Writ-Timestamp: 1793452800
X-Writ-Signature-V1: sha256=4f0c1e...   (HMAC-SHA256 of "1793452800." + body)
X-Writ-Signature: sha256=9b2d7a...      (older: HMAC-SHA256 of the body only)

{
  "event": "notification",
  "title": "Price changed",
  "message": "Espresso machine is now 129.50",
  "context": { "workflow_name": "Shop prices", "result": { "price": 129.5 } }
}
```

Verify `X-Writ-Signature-V1`: it covers the timestamp and the body, so a captured
delivery cannot be replayed later. Compute it over the raw body exactly as received, before any
JSON parsing, and refuse timestamps more than 5 minutes old. The older `X-Writ-Signature` covers the body only and is still sent for older receivers.

```python
import hashlib, hmac, os, time

def is_from_writ(headers, body: bytes) -> bool:
    """headers: the request headers; body: the raw bytes, exactly as received."""
    ts = headers.get("X-Writ-Timestamp", "")
    sig = headers.get("X-Writ-Signature-V1", "")
    if not ts.isdigit() or not sig or abs(time.time() - int(ts)) > 300:
        return False
    expected = "sha256=" + hmac.new(
        os.environ["WRIT_WEBHOOK_SECRET"].encode(),
        f"{ts}.".encode() + body,
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(sig, expected)
```

```typescript
import { createHmac, timingSafeEqual } from "node:crypto";

// headers: lower-cased request headers; rawBody: the bytes exactly as received
export function isFromWrit(headers: Record<string, string | undefined>, rawBody: Buffer): boolean {
  const ts = headers["x-writ-timestamp"] ?? "";
  const sig = headers["x-writ-signature-v1"] ?? "";
  if (!/^\d+$/.test(ts) || !sig || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const expected =
    "sha256=" +
    createHmac("sha256", process.env.WRIT_WEBHOOK_SECRET!).update(`${ts}.`).update(rawBody).digest("hex");
  const a = Buffer.from(sig);
  const b = Buffer.from(expected);
  return a.length === b.length && timingSafeEqual(a, b);
}
```

The [SDKs](https://usewrit.app/docs/sdks) include the same check as `verify_webhook` / `verifyWebhook`.
A delivery counts as received when your server answers with a 2xx status. Otherwise Writ tries up to
3 times in total, 1 then 2 seconds apart, with a 30-second timeout each. Redirects are not followed.

> **limit:** Only saved destinations that have a secret are signed. A URL typed straight into a step is sent without signature headers. Save a destination with its secret over the API (a key with permission to write triggers), then leave the step's URL empty to post to all saved destinations, or pick the ones you want.

```bash
curl -X POST https://api.usewrit.app/api/webhooks/recipients \
  -H "Authorization: Bearer $WRIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "Orders service", "url": "https://example.com/hooks/writ", "secret": "a-long-random-string"}'
```

## On Writ Desktop

Writ Desktop has the same **Automations** builder, and its schedules and automations run
on your computer for free. A few triggers and steps exist only there (marked Desktop in
the tables above). Slack, Discord and Telegram alerts work without an account; email and SMS need a
linked account.

Incoming webhooks are listed under **MCP & APIs → Endpoints → Incoming webhooks**.
An outside system posts to `http://127.0.0.1:8131/v1/hooks/{token}`. If the webhook
was created with a secret, each request must carry `X-Writ-Signature`: `sha256=` plus the hex HMAC-SHA256 of the raw body (no timestamp on Desktop).

```bash
BODY='{"order_id": "A-1042"}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | sed 's/^.* //')

curl -X POST "http://127.0.0.1:8131/v1/hooks/<token>" \
  -H "Content-Type: application/json" \
  -H "X-Writ-Signature: sha256=$SIG" \
  -d "$BODY"
```

That address answers only on your computer. To receive webhooks from other machines, use LAN mode
or a public URL on a paid plan; see [Writ Desktop](https://usewrit.app/docs/desktop).

## Next

-
- [Alerts and notifications](https://usewrit.app/docs/notifications): Channels, recipients and message placeholders for Send Notification.
-
- [Zapier, Make and n8n](https://usewrit.app/docs/integrations): Trigger Writ from automation tools and send them events.
-
- [Monitor a page](https://usewrit.app/docs/monitors): Watch a page and react when it changes.
-
- [Call your API](https://usewrit.app/docs/call): Run an API on demand from your own code.
