> ## Documentation Index
> Fetch the complete documentation index at: https://iii.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# HTTP

> Expose functions as HTTP endpoints with the http worker.

The `http` worker turns your functions into REST routes exposed as HTTP endpoints.

## Before adding the worker

`compose::add` is served by a running Compose daemon. Keep the engine and a daemon for this project
running in separate terminals before using any of the commands below. If this project does not have
a Compose file yet, create `worker-compose.yaml` containing `containers: {}` first.

```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
# terminal 1
iii --config config.yaml

# terminal 2, from the directory that contains worker-compose.yaml
iii compose --namespace dev --engine ws://127.0.0.1:49134
```

`iii compose` without a subcommand starts the Compose daemon. `--namespace` selects its namespace,
and `--engine` connects it to the existing engine. These options are listed in the generated
[CLI reference](https://iii.dev/docs/0-26-0/cli-reference/index.md#iii-compose).

Run the remaining commands from a third terminal in that same project directory:

```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
iii call -n dev compose::add worker=http
```

> [!NOTE]
>
> The http worker's server settings (port, host, CORS, timeouts) are managed at runtime through the
> [configuration worker](https://iii.dev/docs/0-26-0/using-iii/configuration.md).

## Create endpoints

An observer of `http::on-request` with `method` and `path` args is a route. The http worker adds the
route when the observer is added, and the target's return value is the response.

1. In a worker, register the function you want to expose, then observe `http::on-request` with its
   route. If you do not have a worker yet, follow
   [Create a new worker](https://iii.dev/docs/0-26-0/creating-workers/workers.md#create-a-new-worker), then edit its source:

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { registerWorker } from "iii-sdk";
>
> const url = process.env.III_URL;
> if (!url) throw new Error("III_URL must be set");
> const worker = registerWorker(url, {
>   workerName: "my-worker",
>   namespace: "orders",
> });
>
> worker.registerFunction("orders::get", async (req: { path_params: { id: string } }) => ({
>   status_code: 200,
>   body: { id: req.path_params.id, status: "shipped" },
>   headers: { "Content-Type": "application/json" },
> }));
>
> // a request without the tenant header gets 422, and orders::get does not run
> const observer = worker.observe(
>   {
>     function_id: "http::on-request",
>     args: { method: "GET", path: "/orders/:id" },
>     filters: { "input.headers.x-tenant": { $exists: true } },
>   },
>   "orders::get",
> );
>
> await observer.ready();
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import os
>
> from iii import InitOptions, register_worker
>
> worker = register_worker(
>     os.environ["III_URL"],
>     InitOptions(worker_name="my-worker", namespace="orders"),
> )
>
>
> def get_order(req: dict) -> dict:
>     return {
>         "status_code": 200,
>         "body": {"id": req["path_params"]["id"], "status": "shipped"},
>         "headers": {"Content-Type": "application/json"},
>     }
>
>
> worker.register_function("orders::get", get_order)
>
> # a request without the tenant header gets 422, and orders::get does not run
> observer = worker.observe(
>     {
>         "function_id": "http::on-request",
>         "args": {"method": "GET", "path": "/orders/:id"},
>         "filters": {"input.headers.x-tenant": {"$exists": True}},
>     },
>     "orders::get",
> )
>
> observer.ready()
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::runtime::WorkerMetadata;
> use iii_sdk::{Error, InitOptions, RegisterFunction, Source, register_worker};
> use schemars::JsonSchema;
> use serde::Deserialize;
> use serde_json::json;
>
> #[derive(Deserialize, JsonSchema)]
> struct GetOrderRequest {
>     path_params: PathParams,
> }
>
> #[derive(Deserialize, JsonSchema)]
> struct PathParams {
>     id: String,
> }
>
> #[tokio::main]
> async fn main() -> Result<(), Error> {
>     let url = std::env::var("III_URL").expect("III_URL must be set");
>     let worker = register_worker(
>         &url,
>         InitOptions {
>             metadata: Some(WorkerMetadata {
>                 name: "my-worker".into(),
>                 ..Default::default()
>             }),
>             namespace: Some("orders".into()),
>             ..Default::default()
>         },
>     );
>
>     worker.register_function(
>         "orders::get",
>         RegisterFunction::new(|request: GetOrderRequest| {
>             Ok::<_, Error>(json!({
>                 "status_code": 200,
>                 "body": { "id": request.path_params.id, "status": "shipped" },
>                 "headers": { "Content-Type": "application/json" }
>             }))
>         }),
>     );
>
>     // a request without the tenant header gets 422, and orders::get does not run
>     let observer = worker.observe(
>         Source::function("http::on-request")
>             .args(json!({ "method": "GET", "path": "/orders/:id" }))
>             .filters(json!({ "input.headers.x-tenant": { "$exists": true } })),
>         "orders::get",
>     );
>     observer.ready().await?;
>
>     // the connection runs on a thread of its own: park so the process stays up
>     loop {
>         std::thread::park();
>     }
> }
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> package main
>
> import (
> 	"context"
> 	"encoding/json"
> 	"log"
> 	"os"
>
> 	iii "github.com/iii-hq/iii/sdk/packages/go/iii"
> )
>
> func getOrder(ctx context.Context, data json.RawMessage) (any, error) {
> 	var req struct {
> 		PathParams struct {
> 			ID string `json:"id"`
> 		} `json:"path_params"`
> 	}
> 	if err := json.Unmarshal(data, &req); err != nil {
> 		return nil, err
> 	}
> 	return map[string]any{
> 		"status_code": 200,
> 		"body":        map[string]string{"id": req.PathParams.ID, "status": "shipped"},
> 		"headers":     map[string]string{"Content-Type": "application/json"},
> 	}, nil
> }
>
> func main() {
> 	client := iii.RegisterWorker(os.Getenv("III_URL"),
> 		iii.WithName("my-worker"),
> 		iii.WithNamespace("orders"),
> 	)
>
> 	if _, err := client.RegisterFunction("orders::get", getOrder); err != nil {
> 		log.Fatal(err)
> 	}
>
> 	// a request without the tenant header gets 422, and orders::get does not run
> 	observer, err := client.Observe(iii.Source{
> 		FunctionID: "http::on-request",
> 		Args:       iii.Args{"method": "GET", "path": "/orders/:id"},
> 		Filters:    iii.Filters{"input.headers.x-tenant": iii.Op{"$exists": true}},
> 	}, "orders::get")
> 	if err != nil {
> 		log.Fatal(err)
> 	}
>
> 	if err := client.Connect(context.Background()); err != nil {
> 		log.Fatal(err)
> 	}
> 	if err := observer.Ready(context.Background()); err != nil {
> 		log.Fatal(err)
> 	}
>
> 	// the client runs the connection on goroutines of its own: block
> 	select {}
> }
> ```

2. Add the worker to Compose, pointing at its directory:

```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
iii call -n dev compose::add worker=./my-worker
```

The route is set by the observer's `args`:

| Arg | Required | Meaning |
| - | - | - |
| `method` | yes | The HTTP method to match, for example `GET`. |
| `path` | yes | The route path with a leading slash. `/orders/:id` puts `id` in `path_params`. |
| `middleware_function_ids` | no | Functions that run before the target, in order. |
| `public_webhook` | no | `true` also serves the route on the restricted webhook listener. |

The target receives the request as `{ method, path, path_params, query_params, headers, body }`, and
returns `{ status_code, headers, body }`. A second observer of the same method and path shape is
rejected with `HTTP_ROUTE_CONFLICT`; `await observer.ready()` reports it. Disposing the observer
removes the route.

Observer `filters` select requests by anything in them. A request on the route that the filters
reject gets a `422` response, and the target does not run.

For streaming responses and the other configuration options, see the
[http worker docs](https://workers.iii.dev/workers/http).

## Calling the endpoint

Once the observer is active, set `HTTP_WORKER_URL` to the address configured for the http worker and
call the endpoint:

```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
# call the exposed function
curl "$HTTP_WORKER_URL/orders/order-123" -H 'x-tenant: acme'
```


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