# HttpApi: define the API once

- Published: 2026-11-12
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-5-httpapi-define-once/

> Part 5 of a series that builds one backend server on Node with Effect 4. The code is in [devtrillo/effect-on-the-backend](https://github.com/devtrillo/effect-on-the-backend/tree/part-5), and this part is the `part-5` tag.

[Part 4](/writing/effect-backend-4-schema-at-the-boundary/)'s `src/main.ts` had 49 non-blank lines. About half of them were me telling each route which schema to decode with and what to do when decoding failed. The schemas lived in one file, and the routes that used them lived in another, and nothing checked that a client calling `/users` agreed with either.

This part moves both routes into an `HttpApi`. `src/main.ts` drops to 22, and I get an OpenAPI document and a typed client without writing either. One thing gets worse, though, and the document turns out to promise something the server doesn't do.

## The contract

An `HttpApi` is a value. It holds groups, and a group holds endpoints. Each endpoint has a name, a method, a path, and schemas for whatever it reads and returns.[^httpapi] Here are part 4's two user routes as a contract:

```ts title="src/Api.ts"
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api"
import { NewUser, User, UserParams } from "./User.ts"

export const UsersGroup = HttpApiGroup.make("users").add(
  HttpApiEndpoint.get("get", "/users/:id", {
    params: UserParams,
    success: User,
  }),
  HttpApiEndpoint.post("create", "/users", {
    payload: NewUser,
    success: User.pipe(HttpApiSchema.status(201)),
  }),
)

export const Api = HttpApi.make("api").add(UsersGroup)
```

`UserParams` and `NewUser` are part 4's schemas, unchanged. The only new one is `User`, the response. Until now, `User` was a TypeScript interface in `Users.ts`, and an interface can't encode anything. So `User.ts` gained a schema, and `Users.ts` now takes its `User` type from it:

```ts title="src/User.ts (excerpt)"
export const User = Schema.Struct({
  id: Schema.String,
  name: Schema.String,
  email: Schema.optionalKey(Schema.String),
}).annotate({ identifier: "User" })
export type User = typeof User.Type
```

The status code is part of the schema. `HttpApiSchema.status(201)` is how `create` says it answers 201, and an endpoint with no `success` at all answers 204.

There are no handlers in `Api.ts` and no Node imports. That matters later, because the client imports this file.

One thing to know before you build on it. Every export of `effect/http-api` is marked `@stability unstable` in 4.0.5, which means breaking changes are allowed in minor releases. The path lost its `unstable/` segment in 4.0, but Effect's migration guide says moving these modules "does not stabilize their APIs".[^stability] That's why [part 1](/writing/effect-backend-1-what-changed-in-effect-4/) pinned `effect` to exactly 4.0.5.

## The server

Here's all of `src/main.ts` now:

```ts title="src/main.ts"
import { NodeHttpServer, NodeRuntime } from "@effect/platform-node"
import { Effect, Layer } from "effect"
import { HttpRouter, HttpServerResponse } from "effect/http"
import { HttpApiBuilder, HttpApiScalar } from "effect/http-api"
import { createServer } from "node:http"
import { Api } from "./Api.ts"
import { getUser } from "./getUser.ts"
import { Users } from "./Users.ts"

const UsersLive = HttpApiBuilder.group(Api, "users", (handlers) =>
  handlers
    .handle("get", ({ params }) => getUser(params.id).pipe(Effect.orDie))
    .handle("create", ({ payload }) => Users.use((users) => users.create(payload))),
)

const Health = HttpRouter.add("GET", "/health", HttpServerResponse.text("ok"))

const ApiRoutes = HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe(
  Layer.provide(UsersLive),
)

const Server = HttpRouter.serve(Layer.mergeAll(Health, ApiRoutes, HttpApiScalar.layer(Api))).pipe(
  Layer.provide(Users.layer),
  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),
)

Layer.launch(Server).pipe(NodeRuntime.runMain)
```

`HttpApiBuilder.group` takes the contract and a group name, and you hand it one function per endpoint. Each handler gets its input already decoded: `params.id` is a `UserId` and `payload` is a `NewUser`. There's no `schemaPathParams` call and no `catchTag`. Decoding happens before the handler runs, and a handler only runs if it worked.

`HttpApiBuilder.layer` turns the whole contract into routes on part 3's router. `/health` is still a plain `HttpRouter.add` next to it, so you can move routes over one at a time. The bottom four lines are the same as in [part 3](/writing/effect-backend-3-a-node-server-in-20-lines/).

The `Effect.orDie` on `get` is a stopgap. `getUser` can fail with `UserNotFound`, and the contract doesn't say `get` can fail. `orDie` turns the failure into a defect, which is a 500, the same as in part 4. The last section shows what happens without it.

```text title="curl against npm start"
GET  /health                                          200 ok
GET  /users/1                                         200 {"id":"1","name":"Ada"}
GET  /users/abc                                       400 (empty body)
GET  /users/2                                         500
POST {"name":"  Grace  ","email":"grace@example.com","isAdmin":true}
                                                      201 {"id":"2","name":"Grace","email":"grace@example.com"}
POST {"name":"   ","email":"nope"}                    400 (empty body)
POST {"name":                                         400 (empty body)
POST without content-type: application/json           415 Unsupported content-type: application/x-www-form-urlencoded
```

This is the thing that got worse. Part 4's 400s listed every bad field. These are empty. The log still knows why, but the client doesn't:

```text title="npm start (trimmed)"
INFO (#21) http.span=0ms: HttpApiSchemaError: Payload {
  [cause]: SchemaError: Expected a value with a length of at least 1
    at ["name"]
}
```

And it only names `name`. The email was bad too, but HttpApi decodes without part 4's `errors: "all"`, so it stops at the first problem. Part 6 gives the 400 its body back.

The 415 is new as well. Part 4's `schemaBodyJson` parsed a body sent with curl's default form content type. HttpApi turns it away.

**Quiz:** GET /users/1.5. UserId only accepts strings of digits. What happens?

- The handler runs, and getUser fails with UserNotFound: a 500
- A 400 with an empty body, and the handler never runs
- A 404, because no route matches

**Answer:** A 400 with an empty body, and the handler never runs — Params are decoded before the handler. The log says HttpApiSchemaError: Params, Expected a positive integer at ["id"].

- Not "The handler runs, and getUser fails with UserNotFound: a 500": The handler never sees an id that didn't decode.
- Not "A 404, because no route matches": The path matches /users/:id. It's the value that's wrong.

## The client

The same contract gives you a client. It's typed from the schemas, and it decodes responses with them too:

```ts title="src/client.ts"
import { Effect } from "effect"
import { FetchHttpClient } from "effect/http"
import { HttpApiClient } from "effect/http-api"
import { Api } from "./Api.ts"
import { UserId } from "./User.ts"

const program = Effect.gen(function* () {
  const client = yield* HttpApiClient.make(Api, { baseUrl: "http://localhost:3000" })
  const created = yield* client.users.create({
    payload: { name: "Grace", email: "grace@example.com" },
  })
  const found = yield* client.users.get({ params: { id: UserId.make(created.id) } })
  console.log({ created, found })
  yield* client.users.create({ payload: { name: "", email: "nobody@example.com" } })
})

program.pipe(Effect.provide(FetchHttpClient.layer), Effect.runPromise).catch(console.error)
```

```text title="node src/client.ts"
{
  created: { id: '4', name: 'Grace', email: 'grace@example.com' },
  found: { id: '4', name: 'Grace', email: 'grace@example.com' }
}
{
  _tag: 'SchemaError',
  message: 'Expected a value with a length of at least 1\n  at ["name"]'
}
```

The second `create` never left the process. The server log shows the POST and the GET, and nothing after them. The client encodes the payload with `NewUser` before sending it, so an empty name fails on the caller's side.

My first version passed `created.id` straight to `get`, and tsc refused: `Type 'string' is not assignable to type 'string & Brand<"UserId">'`. It was right. The `User` schema says `id` is a string, and `UserParams` wants a `UserId`, so the contract had caught two of my own schemas disagreeing. `UserId.make` checks the pattern and adds the brand.

<Quiz
  question={
    'The server trims names, so POST {"name":"  Grace  "} with curl is a 201. What does client.users.create({ payload: { name: "  Grace  ", email: "grace@example.com" } }) do?'
  }
  options={[
    {
      text: "Sends it, and gets back Grace, trimmed",
      explanation:
        "That's what curl gets. The client checks the payload before it sends anything.",
    },
    {
      text: 'Trims it locally, then sends "Grace"',
      explanation:
        "Encoding goes from the decoded type to JSON. It checks that the value is already trimmed. It doesn't trim it.",
    },
    {
      text: "Fails with a SchemaError and sends nothing",
      correct: true,
      explanation:
        '"Expected a string with no leading or trailing whitespace". The client treats the payload as already decoded, and an untrimmed string isn\'t a valid decoded name.',
    },
  ]}
/>

## The document

`openapiPath: "/openapi.json"` serves an OpenAPI 3.1 document built from the contract, and `HttpApiScalar.layer(Api)` serves a docs page for it at `/docs`. Swagger UI is the same idea with `HttpApiSwagger.layer`. If you want the JSON without a server, `OpenApi.fromApi(Api)` returns it.

```json title="curl localhost:3000/openapi.json (excerpt)"
"/users": {
  "post": {
    "operationId": "users.create",
    "responses": {
      "201": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/User_1" } } } }
    },
    "requestBody": {
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": { "name": { "type": "string" }, "email": { "type": "string" } },
            "required": ["name", "email"],
            "additionalProperties": false
          }
        }
      }
    }
  }
}
```

Everything reads from one value, so change the contract and all three move with it. Not every change is a compile error, though. Here are four edits I made to `src/Api.ts` and `src/User.ts`, one at a time:

**One edit to the contract, and what the server, the client and the OpenAPI document do.**

| Edit | Server | Client | OpenAPI |
| --- | --- | --- | --- |
| Add a remove endpoint (`HttpApiEndpoint.delete("remove", "/users/:id", { params: UserParams })`) | tsc fails at HttpApiBuilder.group: not assignable to type "Endpoint not handled: remove". | Compiles. client.users.remove exists now, and nothing calls it yet. | DELETE /users/{id} appears, documented as a 204, because the endpoint has no success schema. |
| Delete the get endpoint (`HttpApiEndpoint.get("get", "/users/:id", …) removed`) | tsc fails in src/main.ts: Argument of type '"get"' is not assignable to parameter of type '"create"'. | tsc fails in src/client.ts: Property 'get' does not exist. | /users/{id} is gone from the document. |
| Make email optional (`email: Schema.optionalKey(…)`) | Compiles. POST {"name":"Grace"} now answers 201 with no email. | Compiles. src/client.ts still sends an email, which is still allowed. | email leaves the body's "required" list. |
| Drop status(201) from create (`success: User`) | Compiles. POST /users answers 200 instead of 201. | Compiles, and still decodes the created user. | POST /users is documented as 200. |

Two of the four compile without a word. Dropping `status(201)` changes what every caller gets back, and tsc has nothing to say about it, because nothing in the types depends on the status code. The document is the only place the change shows.

## The gotchas, and when not to bother

Look at that request body again. `src/part-5/openapi.ts` prints the parts of the document that don't match the server:

```text title="node src/part-5/openapi.ts"
GET  /users/{id} responses: [ '200' ]
POST /users responses:      [ '201' ]
POST /users body: {"type":"object","properties":{"name":{"type":"string"},"email":{"type":"string"}},"required":["name","email"],"additionalProperties":false}
components: [ 'User_1', 'User' ]
Int id pattern: ^[+-]?\d*\.?\d+(?:[Ee][+-]?\d+)?$
pattern matches "1.5": true
```

- **The spec says `additionalProperties: false`, but the server drops extras.** The `isAdmin` POST above was a 201. The document forbids extra keys, and the server accepts them and throws them away.
- **There are no 400s in the spec.** Every endpoint here can answer 400, and the document lists only the success status.
- **The checks don't make it into the spec.** The id is documented as a plain string, without part 4's pattern, and `name` has no minimum length.
- **An `Int` param's pattern matches `1.5`.** Part 4 kept ids as strings, so this one isn't in the server. But if you declare a param as `Schema.Int`, the documented pattern accepts `1.5`, and the server rejects it with a 400.
- **`User_1` is the same schema as `User`.** `status(201)` makes a copy, and the document has both components.
- **The client checks payloads against the decoded type**, as in the second quiz. A value the server would happily clean up can fail before it's sent.
- **Any import loads about 5 MB of docs UI.** In 4.0.5, importing anything from `effect/http-api` evaluates the bundled Scalar and Swagger assets, whether you serve `/docs` or not. On my machine, `effect` plus `effect/http` was 104 MB of memory, and adding `effect/http-api` made it 153 MB. The fix is on Effect's `main` branch and hasn't been released.[^lazy] - **Sharing the contract with a browser isn't free.** When I bundled an `HttpApiClient` for a contract like this one with esbuild for the browser, it came to 118 KB gzipped. None of the docs UI ended up in it.

When not to bother: a route nobody else calls. If the only caller is your own code in another service, that's a question for part 16, which compares this with Effect's RPC.

## Run it

```sh
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-5
npm install
npm start
```

Open `localhost:3000/docs` for the Scalar page, and run `node src/client.ts` in another terminal. `src/part-5/` has the OpenAPI script above and the type errors below.

## What the types tell you

`src/part-5/types.ts` is type-check only, with an `@ts-expect-error` on each line that shouldn't compile. Here's `npm run check` without them:

```text title="npm run check (without the expect-error lines, trimmed)"
error TS2322: Type 'Handlers<…, "get">' is not assignable to type '"Endpoint not handled: create"'.
error TS2375: Type 'Effect<{ id: string & Brand<"UserId">; fullName: string; }, never, never>' is not assignable to type 'Effect<{ readonly id: string; readonly name: string; readonly email?: string; } | HttpServerResponse, never, never>'
  Property 'name' is missing in type '{ id: string & Brand<"UserId">; fullName: string; }'
error TS2322: Type 'string' is not assignable to type 'string & Brand<"UserId">'.
error TS2339: Property 'remove' does not exist on type '{ readonly get: …; readonly create: … }'.
error TS2375: Type 'Effect<{ … }, UserNotFound, Users>' is not assignable to type 'Effect<{ … } | HttpServerResponse, never, Users>'
  Type 'UserNotFound' is not assignable to type 'never'.
```

In order: a group that handles `get` and forgets `create`, a handler that returns `fullName`, a client call with a plain string id, and a client call to an endpoint that doesn't exist.

The last one is `get` without the `Effect.orDie`. The handler's error slot has to be `never`, because the contract doesn't declare any errors for `get`, and `UserNotFound` isn't `never`. The contract has no way to say "this endpoint can answer 404", so I made the error a defect to get it past tsc. Part 6 lets `get` declare `UserNotFound` with its own status code, and `/users/2` finally becomes a 404.

Next in the series: typed errors become status codes.

[^httpapi]: [`HTTPAPI.md`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/packages/effect/HTTPAPI.md) at the `effect@4.0.5` tag is the HttpApi guide. The v4 docs site has no HttpApi page yet.

[^stability]: [`MIGRATION.md`](https://github.com/Effect-TS/effect/blob/main/MIGRATION.md) lists `http-api` among the modules that moved out of `unstable/`, and says the move doesn't stabilize them. The `@stability unstable` tags are in `effect/dist/http-api/index.d.ts`.

[^lazy]: The unreleased changeset is [`http-api-lazy-docs-assets.md`](https://github.com/Effect-TS/effect/blob/main/.changeset/http-api-lazy-docs-assets.md): "Importing the module no longer evaluates about 5 MB of embedded JavaScript and CSS."

- **Part 6 — Typed errors become status codes**: UserNotFound carries its own 404, the client catches it by name, and every bad request gets a 400 that says what was wrong.
