# HTTP and webhooks

> Call any web API from a flow with the Call an API step, and let another system start a flow by calling a webhook address. Covers connections, signing, retries, limits and how to test both.

Source: https://docs.go-lumen.ai/connectors/http-and-webhooks

Two connections cover systems that have no connector of their own. A web service connection lets a flow call an API with the **Call an API** step. A webhook connection gives another system an address to call, and each call starts a flow with the data it sends.

-   One connection per system
-   Admin to connect
-   Secrets stay out of flows

## Call an API

### Create the connection

A **Web service (HTTP API)** connection holds what is the same for every call to one system: where it lives, the headers every call carries, and how to sign in. The key, token or password is kept apart and a step cannot read it.

| Setting | What it does |
| --- | --- |
| **Base address** (`baseURL`) | Where the API lives, such as `https://api.example.com/v1`. Each call adds its path to it. Required, and `https` only. |
| **Headers on every call** (`defaultHeaders`) | One per line as `Name: value`. Never a key or password. |
| **How it signs you in** (`auth`) | **No sign-in** (`none`), **Bearer token** (`bearer`, secret key `token`), **User and password** (`basic`, keys `username` and `password`), **API key in a header** (`apiKeyHeader`, key `key`) or **API key in the address** (`apiKeyQuery`, key `key`). |
| **Header or parameter name** (`authName`) | For an API key, the header (`X-Api-Key`) or the address parameter (`api_key`) it goes in. |

**Console:**

1.  Open **Connectors**, click **Add connection** and choose **Web service (HTTP API)**.
2.  Give it a **Name**, such as `Billing API`, and fill in the **Base address**.
3.  Choose **How it signs you in** and enter the key, token or password in the credentials fields. It is stored apart from the connection and never shown again.
4.  Click **Test connection**. Lumen sends a HEAD request (a GET where HEAD is refused) to the base address with the sign-in, and tells you whether it was reachable and accepted. Then click **Add**.

**CLI:**

```bash title="Connect a web service from a terminal"
lumen connect http billing-api \
  --set baseURL=https://api.billing.example/v1 \
  --set auth=bearer \
  --secret-env token=BILLING_API_TOKEN
```

**YAML:**

```yaml title="billing-api.yaml"
apiVersion: lumen.ai/v1alpha1
kind: Connector
metadata:
  name: billing-api
  namespace: tenant-acme
spec:
  classRef: {name: http}
  config:
    baseURL: https://api.billing.example/v1
    defaultHeaders: {Accept: application/json}
    auth: bearer
  credentials:
    secretRef: {name: lumen-conn-billing-api}
```

The token is the key `token` of the Secret `lumen-conn-billing-api`. Write it through the console or `lumen connect`, never in the resource.

A flow that goes through a connection runs only while the connection is ready: it exists, is not paused, and has its credentials. Otherwise the run is refused up front, with the reason.

### Add the step

1.  In the editor, hover the line where the call should go, click **+** and choose **Call API**.
2.  Under **Connection**, pick the web service. **None, a public API** calls any public address that needs no sign-in, and then you give the whole **URL**. With a connection, you give a **Path** under its base address instead.
3.  Choose the **Method** (`GET`, `POST`, `PUT`, `PATCH` or `DELETE`), and add **Query** values and **Headers** if you need them.
4.  For `POST`, `PUT` and `PATCH`, choose the **Body type** (**JSON**, **Text** or **Form**) and write the **Body**. Put fields inside strings, such as `"{order.total}"`.
5.  Under **Response fields**, click **Add a field** for each value of the JSON answer that later steps need: a **Field name**, a path such as `$.invoice.id` under **Where in the answer**, and a **Type**.
6.  Click **Done**.

![The settings of the step 1. Call an API, scrolled to the lower half. Query and Headers have Add a query value and Add a header buttons. Body type offers JSON, selected, Text and Form. Body is an empty box with the note JSON, put fields inside strings, for example n2.total in braces. Response fields has one row, with the field name orderId, the path $.order.id and the type Text, and an Add a field button. An Advanced section is collapsed.](https://docs.go-lumen.ai/img/connectors/http-and-webhooks-03-call-an-api.png)

*Body and response fields of a POST. The status and text of the answer are always available as status and body.*

Open **Advanced** for three more settings:

| Setting | What it does |
| --- | --- |
| **Retry-safe key** (`idempotencyKey`) | Sent as the `Idempotency-Key` header, so a repeat of the step does not repeat the call on an API that honours it. The console fills in a key made from the run and the step. |
| **Time limit (seconds)** (`timeoutSeconds`) | How long one request may take: 20 by default, 60 at most. |
| **Counts as success** (`expect`) | The statuses that are a success, such as `200, 201`. Any `2xx` by default. |

### What the step gives back

The step always adds `status` (a number) and `body` (the answer as text, cut at 4 KB, with credentials replaced by `***`). Each response field becomes a typed field, `string`, `number`, `date`, `money` or `boolean`, found by its path (`$.invoice.total`, `$.items[0].id`) in the JSON answer. A value the answer lacks is recorded as missed. A value of the wrong type fails the step and names the field.

### Retries and limits

|  |  |
| --- | --- |
| Retries | A `GET`, `HEAD`, `PUT` or `DELETE` is retried up to three times on a network failure, a timeout, `429` or `5xx`, with a growing wait (and `Retry-After`, up to 5 seconds). A `POST` or `PATCH` is sent once, and its failure is final, except `429`, where the API says it did not process the request. |
| Size | An answer is read to 1 MB. A bigger one fails the step. A request body over 1 MB is never sent. |
| Redirects | One, to the same host, never from `https` to `http`. |
| Where it can go | Only the connection's own host. A path can go deeper under the base address, never out of it. Addresses in private ranges (such as `10.x` and `192.168.x`), loopback and cloud metadata addresses are refused. |

A step cannot carry a credential. A header that looks like one (`Authorization`, `X-Api-Key`, or any name with `token`, `secret`, `passw` or `signature`) is refused in the step and in a connection's default headers. Credentials belong to the connection.

A step that changes something outside Lumen (any method but `GET`) only previews when you test it in the editor: it shows the method, the address, the headers (credentials as `***`) and the size of the body, and calls nothing. Test a `GET` to see a real answer.

## Receive a webhook

### Create the webhook

An **Incoming webhook** connection is an address other systems call to start your flows.

| Setting | What it does |
| --- | --- |
| **Check a signature** (`signature`) | **Secret in the address (simplest)** (`none`): anyone with the address can call it, so keep it private. **HMAC-SHA256 signature (more secure)** (`hmac-sha256`): every call must also carry a signature of its body. |
| **Signature header** (`signatureHeader`) | The header the signature arrives in. Empty is `X-Signature-256`, as `sha256=<hex>` or the hex alone. |

**Console:**

1.  Open **Connectors**, click **Add connection** and choose **Webhook**. Give it a **Name**, such as `Orders webhook`.
2.  Choose **Check a signature** and click **Add**.
3.  Open the connection and click **Show the address**. Admins only can see it. **Copy address** copies it, and **Make a new address** replaces it.
4.  With signing on, the panel also shows the signing secret, with **Copy signing secret** and **Make a new signing secret**. Give it to whoever signs the calls.

![A webhook connection named Orders webhook, Ready, with its address shown. The text says to call this address with a POST, then shows the address in a box with buttons Copy address, Make a new address and Hide. A warning says anyone with this address can start your flows. A section on signing says calls must also be signed with HMAC-SHA256 using the secret shown, with buttons to copy it and to make a new one. An example block shows a curl command that signs the body and posts it with a Content-Type and a signature header.](https://docs.go-lumen.ai/img/connectors/http-and-webhooks-01-webhook-address.png)

*The address holds a secret, so it is shown only when an admin asks. The addresses here are placeholders, and the example uses the header this connection is set to.*

**YAML:**

```yaml title="orders-hook.yaml"
apiVersion: lumen.ai/v1alpha1
kind: Connector
metadata:
  name: orders-hook
  namespace: tenant-acme
spec:
  classRef: {name: webhook}
  config:
    signature: hmac-sha256
    signatureHeader: X-Signature-256
```

Lumen writes `config.endpointId` when the connection is created. The address's secret part and the signing secret live in a Secret that no workspace role can read, and an admin reads them through the console.

The address looks like this:

```text
POST https://<hooks host>/hooks/<endpoint id>/<token>
```

The endpoint id is not a secret and never changes. The token is the secret half. **Make a new address** replaces the token for good, and the old address stops working within seconds for everyone who calls it. Keep the address out of public places and, where a gateway's access log would keep the path, sign the calls.

### What a call does

| Situation | Answer |
| --- | --- |
| Accepted | `202` with `runId`, `runIds` and the intake id. A flow that is suspended or has the trigger switched off is listed as skipped, with the reason, and the call still arrived. |
| Unknown address, or a wrong token | `404`, empty, the same for both |
| Signing is on and the signature is missing or wrong | `401` |
| The connection is paused | `423` |
| Too many calls | `429` with `Retry-After` |
| A body over 1 MB | `413` |
| A content type that is not JSON, text or a form | `415` |

**Duplicates.** The same `Idempotency-Key` header, or without one the same body, within the same minute is one arrival. It starts nothing again and is answered the same, with `duplicate: true`. So a sender that retries on a timeout does not start the flow twice. For anything longer, give the call an `Idempotency-Key` and use **Skip duplicates** in the flow.

**Signatures.** With `hmac-sha256`, the signature is the HMAC-SHA256 of the raw body with the signing secret, in hex, in the signature header.

### Start a flow from it

Add the trigger **A webhook is called**, and pick the webhook connection. The body of the call is the run's text. A JSON body's top-level text, number and yes/no values are fields of their own names, and a form's values are text fields. To use something deeper, name it under **Fields from the body**: a **Field name**, a path such as `$.order.total` under **Where in the body**, and a **Type**. Only the fields you name are known to the editor, so map what a later step reads. A mapped value the body lacks is recorded as missed, not as a failure.

![The settings of the trigger A webhook is called. A line says A call to the webhook Orders webhook starts this flow. Under Fields from the body, one row has the field name orderTotal, the path $.order.total and the type Text. An Add a field button follows.](https://docs.go-lumen.ai/img/connectors/http-and-webhooks-02-webhook-trigger.png)

*Fields from the body. Each is found by a path and typed.*

## Example: an order becomes an invoice

An order system calls the webhook. The flow creates an invoice in the billing system and tells your admins its id in the app. It uses the two connections above, `orders-hook` and `billing-api`.

```yaml title="orders-to-invoices.yaml"
apiVersion: lumen.ai/v1alpha1
kind: Flow
metadata:
  name: orders-to-invoices
  namespace: tenant-acme
spec:
  displayName: Invoice every order
  triggers:
    - id: order
      ref: {name: webhook-received}
      connectorRef: {name: orders-hook}
      config:
        mapping:
          - {name: orderId, type: string, jsonPath: $.order.id}
          - {name: total, type: number, jsonPath: $.order.total}
      next: [invoice]
  nodes:
    - id: invoice
      stepRef: {name: http-request}
      config:
        connectorRef: billing-api
        method: POST
        path: /orders/{order.orderId}/invoice
        bodyType: json
        body: '{"order": "{order.orderId}", "total": {order.total}}'
        idempotencyKey: "invoice-{order.orderId}"
        timeoutSeconds: 20
        expect: [200, 201]
        outputs:
          - {name: invoiceId, type: string, jsonPath: $.invoice.id}
          - {name: invoiceUrl, type: string, jsonPath: $.invoice.url}
      next: [mail]
    - id: mail
      stepRef: {name: notify-in-app}
      config:
        to: admins
        title: "Invoice {invoice.invoiceId} created"
        body: "Order {order.orderId} is invoiced: {invoice.invoiceUrl}"
```

## Test both

**Test the webhook** with a call from a terminal. The console's example fills in your address and secret. Without signing it is a plain `POST`:

```bash title="Call a webhook (use your own address)"
curl -X POST 'https://<hooks host>/hooks/<endpoint id>/<token>' \
  -H 'Content-Type: application/json' \
  -d '{"order": {"id": "A-1042", "total": 1240.5}}'
```

With signing, sign the exact body bytes:

```bash title="Call a signed webhook"
BODY='{"order": {"id": "A-1042", "total": 1240.5}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SIGNING_SECRET" | sed 's/^.* //')
curl -X POST 'https://<hooks host>/hooks/<endpoint id>/<token>' \
  -H 'Content-Type: application/json' \
  -H "X-Signature-256: sha256=$SIG" \
  -d "$BODY"
```

A `202` with a `runId` means a run started. Open **Runs** to see it and the trigger's fields. A `404` means the address or token is wrong, and a `401` means the signature does not match the body. The connection's **Test connection** button cannot call a webhook for you and says so.

**Test the step** in the editor: open it and use its **Test** tab. A `GET` makes the real call. Any other method shows what it would send. To try a change for real, run the flow on a test document and check the run.

## Next steps

[TriggersEvery way to start a flow, and the Start only when condition.](https://docs.go-lumen.ai/build/triggers.md)[Data and placeholdersHow `{order.total}` finds the value a trigger or step produced.](https://docs.go-lumen.ai/concepts/data-and-placeholders.md)[Runtime APIStart runs from your own code with an API key instead of a webhook.](https://docs.go-lumen.ai/api/runtime-api.md)[When a run failsWhat a refused call or a wrong-type answer looks like in a run.](https://docs.go-lumen.ai/build/when-a-run-fails.md)
