Overview
Every API in Courier is described by three building blocks:
courier— returns the heads endpoints are built from, carrying whatever settings they sharedefineGroup— organizes related endpoints under a common URL prefixdefineApi— creates an API source with a base URL, groups, and shared options (middleware, headers, etc.)
All three are imported from @noverax/courier/define.
defineGroup
Groups related endpoints under a URL prefix:
import { courier, defineGroup } from "@noverax/courier/define"
const { endpoint } = courier()
type User = { id: string; name: string; email: string }
export const users = defineGroup({
prefix: "users",
endpoints: {
getAll: endpoint.get("").response<User[]>(),
getById: endpoint.get(":id").variables<{ id: string }>().response<User>(),
create: endpoint.post("").variables<{ name: string; email: string }>().response<User>(),
update: endpoint.put(":id").variables<{ id: string; name: string }>().response<User>(),
remove: endpoint.del(":id").variables<{ id: string }>().response<null>(),
},
})A group may hold groups of its own, under groups, to any depth: caller.billing.invoices.list() reaches list in the invoices group inside billing, at both groups' prefixes in turn. See Groups inside groups.
courier
courier() returns three heads and extend. Which head you start from declares what the endpoint is, not just what it returns:
endpoint— an HTTP endpoint. The verb that addresses it — named on the chain, or called by a.via()closure — decides whether it reads or writes:get,head,optionsandqueryread, and one that declares.cache()is proxied as aGETa CDN can cache, any other as aPOST— see GET or POST;post,put,patchanddelwrite, and are proxied as aPOST.stream— server-sent events.channel— a WebSocket channel.
Streams and channels are covered in Streams & Channels.
From a head you chain the steps that shape the endpoint: a verb with its path — or .via() with a closure that builds the request — and the slots .variables() and .response():
const { endpoint } = courier()
// Explicit types — for an API that publishes no usable schema
endpoint.get(":id").variables<{ id: string }>().response<User>()
// Response only — the caller passes nothing
endpoint.get("").response<User[]>()
// With schema — types inferred from Zod/Valibot/ArkType, and validated at runtime
endpoint.post("").variables(CreateUserSchema).response(UserSchema).via() receives http — an object with typed HTTP methods (get, post, put, patch, del, head, options, query), and path, which puts a value into the path as text — and optionally vars (the variables).
The closure runs once as the endpoint is defined, with stand-ins for the variables, to learn the method and path it addresses. It then runs on every call and on every attempt a retry makes, with the call's own variables and a client that sends the request; a stream's or a channel's closure runs each time a subscription opens. So it describes the request and nothing more: a counter it bumps, a line it logs or a token it fetches would run each of those times, the stand-ins included. Work that belongs to a call is middleware's.
A closure reads or writes as the verb it calls does: one that calls http.get is a read — retried, cacheable, taken by the query hooks — and one that calls http.post is a write. A closure that calls a reading verb on one path and a writing verb on another names the endpoint's kind with .reads() or .writes(); until it does, it is no endpoint, and a group refuses it with that reason. Every call keeps to the kind: the endpoint is defined from the path its closure took with stand-ins, so a call on which the closure calls a verb of the other kind is refused with ConfigurationError("ENDPOINT_VERB_KIND") before anything is sent.
const { endpoint } = courier()
// A long question goes in a body, a short one in the address: either way, a read
endpoint
.variables<{ q: string; tags: string[] }>()
.via((http, v) => (v.tags.length > 20 ? http.post("search", v) : http.get("search", v)))
.reads()
// A GET that changes something is a write: sent once, its answer never kept
endpoint.get("unsubscribe").variables<{ token: string }>().writes()A base can carry what a whole vendor surface shares, so no endpoint repeats it:
const vendor = courier({ timeout: 10_000, middleware: [bearer] })
const { endpoint } = vendor
// Both inherit the timeout and the middleware
endpoint.get("").response<User[]>()
endpoint.post("").response<User>()HTTP Methods
http.get() // GET /users
http.get(":id", vars) // GET /users/5 (path param from vars)
http.post("", vars) // POST /users with JSON body
http.put(":id", vars) // PUT /users/5 with JSON body
http.patch(":id", vars) // PATCH /users/5 with JSON body
http.del(":id", vars) // DELETE /users/5
http.options(":id", vars) // OPTIONS /users/5 — what the resource allows
http.query("search", vars) // QUERY /users/search with JSON body — a readThe second argument is what the call sends: the body of a write or a QUERY, or the query string of any other read. Left out, the endpoint's own variables are sent; passed as undefined, nothing is, so a write can put a value in the query string alone. The path is filled from the endpoint's variables either way, and a key of the second argument that names one of the path's parameters is taken out of what is sent, as it is from the variables — a value there neither changes the path nor reaches the body. To send a path parameter in the body too, give the whole body in the third argument's json, which is sent as it is — the variables then only fill the path, as the DELETE below shows:
endpoint
.variables<{ id: number; name: string }>()
.via((http, { name }) => http.post(":id/rename", undefined, { searchParams: { name } }))
// → POST /pets/5/rename?name=rex (no body)
endpoint
.variables<{ id: number; name: string }>()
.via((http, v) => http.put(":id", { id: v.id, name: v.name }))
// → PUT /pets/5 Body: {"name":"rex"} — :id takes the id, and the body leaves it outThe third argument takes per-call options. A body or json named there is sent as the request body, and the variables then only fill the path; its headers are sent as written, whatever their name. This is also how a DELETE carries a body, for an API that requires one:
endpoint
.variables<{ id: number; message: string; sha: string }>()
.via((http, { id, ...reason }) => http.del(":id", { id }, { json: reason }))
// → DELETE /files/7 Body: {"message":"…","sha":"…"}
endpoint
.variables<{ file: Blob }>()
.via((http, v) => http.put("raw", undefined, { body: v.file, headers: { "content-type": "image/png" } }))Asking with a body: QUERY
HTTP QUERY is a read whose question travels in the body: a filter too long for an address, or too structured to flatten into one — nested conditions, a list of ids, a query language. endpoint.query(path) addresses one. It reads as get does — it is retried, its answer may be kept with .cache(), the query hooks take it, and the proxy carries it as any read, as a GET only where it declares .cache() and its variables fit in an address — and it sends its variables as post does, its path filled from them and the rest as a JSON body:
const Filter = z.object({ team: z.string(), status: z.array(z.enum(["active", "invited"])) })
const people = defineGroup({
prefix: "people",
endpoints: {
search: endpoint.query("search").variables(Filter).response(z.array(Person)),
},
})
// → QUERY /people/search Body: {"team":"core","status":["active"]}QUERY needs an upstream that takes it: Node 22 and later parse it, and so do the mock servers Studio runs. An API that answers its searches over POST instead stays a post declared .reads().
An API that takes its writes url-encoded, as Stripe and Twilio do, gets a body formBody writes from the fields. Each field is written as OpenAPI's encoding would name it — by default an array repeats its field and an object's properties are fields of their own; deepObject puts an object's properties, and its arrays' items, in brackets:
import { courier, formBody } from "@noverax/courier/define"
endpoint
.variables<{ email: string; metadata?: Record<string, string> }>()
.via((http, fields) =>
http.post("customers", undefined, {
body: formBody(fields, { metadata: { style: "deepObject", explode: true } }),
}),
)
// → POST /customers Body: email=ada%40example.com&metadata%5Bplan%5D=proEach value is written as JSON writes it in the fields, its own toJSON asked first, so a direct call and a call through the proxy send the same body: a date is its ISO string; what JSON leaves out of an object — undefined, a function, a symbol — is not sent, a field of its own included, and an item of a list it writes as null is sent empty; a value JSON writes as null — null, NaN, a date that is no date — is sent empty; and a file, a Set, a Map or a BigInt is refused with a ConfigurationError whose code is VARIABLE_NOT_ENCODABLE. formQuery writes its values the same way, and leaves out a field JSON writes as null, as the client leaves one out of a query.
An API that takes only multipart/form-data gets a body multipartBody writes: a form whether a file is among the fields or not, each field written as a direct call writes a record that holds a file — see An API that takes only a form:
import { courier, multipartBody } from "@noverax/courier/define"
endpoint
.variables<{ title: string; cover?: Blob }>()
.via((http, fields) => http.post("covers", undefined, { body: multipartBody(fields) }))
// → POST /covers Body: multipart/form-data, a cover among its parts or notA read writes its variables into the query in OpenAPI's default style, form exploded: a list repeats its name and an object's properties become names of their own. Each value is written as JSON writes it in the record a proxy call carries, its own toJSON asked first, so a direct call and a proxy call send the same query: a date is its ISO string, and a value JSON leaves out or writes as null — NaN, a date that is no date — is left out. A parameter declared in another style — Stripe's deepObject filters, a comma- or pipe-joined list — is written by formQuery, which takes the same encodings as formBody and leaves out a field that is undefined or null:
import { courier, formQuery } from "@noverax/courier/define"
endpoint
.variables<{ created?: { gte?: number }; expand?: string[] }>()
.via((http, query) =>
http.get("customers", formQuery(query, {
created: { style: "deepObject", explode: true },
expand: { style: "deepObject", explode: true },
})),
)
// → GET /customers?created%5Bgte%5D=1680000000&expand%5B0%5D=taxA stream of events is opened the same way: its closure takes the stream's own get, and the query is written as formQuery writes it.
import { courier, formQuery } from "@noverax/courier/define"
const { stream } = courier()
stream
.variables<{ fields?: string[] }>()
.via((sse, query) => sse.get("events", formQuery(query, { fields: { style: "form", explode: false } })))
.response<{ status: string }>()
// → GET /events?fields=status%2CtotalresponseType reads one endpoint's answer as "text", "blob", "arrayBuffer" or "formData" when its source reads the rest as JSON — a CSV export, a PDF. An error answer is still read as the source reads it, since it explains the error in its own form:
endpoint
.variables<{ month: string }>()
.via((http, vars) => http.get("reports/:month/export", vars, { responseType: "text" }))
.response<string>()Path Parameters
The :param syntax extracts values from variables automatically:
endpoint.get(":id/posts/:postId").variables<{ id: string; postId: string }>().response<UserPost>()
// caller.users.getUserPost({ id: "1", postId: "42" })
// → GET /users/1/posts/42A parameter may share its segment with text, as :id.json does, or end where its braces do, as files/{id}abc does; {+name} takes a value with its slashes, as Google's v1/{+name} takes projects/p/operations/o; and :: is one colon the path sends as written, for a Google-style method: index::inspect is requested as index:inspect. A path that writes a fragment, items#top, is refused where it is declared.
A parameter can also come from pathOptions on the source or the group, so the variables type does not have to list it. One that neither provides fails the call before any request is made, with an HTTPError 400 whose message names it: Missing required path parameter "postId": pass it in the variables, or return it from pathOptions. See Path Parameters.
Default variables
Some APIs ask for a variable that is nearly always the same — a page size, a grouping. .defaults() names what the endpoint sends when a call leaves a variable out, and the caller may then leave it out:
const { endpoint } = courier()
const news = defineGroup({
prefix: "news",
endpoints: {
byGroup: endpoint
.get("")
.variables<{ group: string; groupBy: "year" | "month"; page?: number }>()
.defaults({ groupBy: "year" }),
},
})
// caller.news.byGroup({ group: "press" }) → GET /news?group=press&groupBy=year
// caller.news.byGroup({ group: "press", groupBy: "month" }) → GET /news?group=press&groupBy=monthThe call's own value wins, and a variable sent as undefined counts as left out. The defaults are filled in where the call is made — on the server for a browser's call through the proxy, which therefore sends less — and before the variables are validated, so a schema that requires groupBy passes. They are copied into each call, the top-level variables only, and variables that are no object, a form say, are left as they are; a record sent on as it arrives takes them in the form it goes as. A default names a variable the endpoint has, as data a request can carry; anything else is refused where the endpoint is defined, with ConfigurationError("DEFAULTS_INVALID"). A second .defaults() adds to the first.
Studio's Playground starts the endpoint with its defaults set and lists each as the default it is, the OpenAPI document gives each its default and no longer requires it, and an agent's tool shows it the same way.
Mapping the answer
.map() maps an endpoint's answer to what its call resolves to, once the response schema has checked it: unwrap an envelope, read a header beside the data, build a type of your own. A stage is handed the data and the answer's status and headers, and returns what the next stage — or the caller — gets. Several run in the order they are named, an asynchronous one too, and the call is typed with what the last one gives:
const { endpoint } = courier()
endpoint
.get("users")
.response<Array<{ id: string }>>()
.map((users, answer) => ({ users, total: Number(answer.headers.get("x-total-count")) }))
// caller.users.page() → Promise<{ users: { id: string }[]; total: number }>The stages run where the call is made — on the server for a browser's call through the proxy, so the page gets what they gave and nothing they left out, sent on as JSON. The page's call is typed with what JSON gives back of it, Proxied<T> from @noverax/courier/define: a type JSON keeps whole stays as it is, a Date arrives as its ISO string, a Set or a Map as an empty object, a function is left out, and undefined in a list or as the whole answer is null. Bytes, a Blob and a FormData travel as themselves. A BigInt fails the call, as JSON writes none, so give it as text. .raw keeps the answer's status and headers beside the mapped data, an after middleware sees the mapped data, and a kept answer is the mapped one. A streamed answer (stream: true) is its reader's, so no stage runs on it. OpenAPI, the mocks and Studio describe the answer as the upstream sends it, as the schema does; an agent's tool returns what the stages gave, so it names no output schema. .response() comes before .map(): named after it, the schema would check what no stage gave, and the chain refuses it.
An envelope around every answer
An API that wraps each answer — { success: true, data }, or { success: false, error } — is unwrapped where its endpoints are described. The envelope's schema checks the answer, and one stage hands on the data or fails the call with an HTTPError that carries the envelope:
import { HTTPError } from "@noverax/courier/client"
import { type AnswerHead, courier } from "@noverax/courier/define"
import { z } from "zod"
const Envelope = <T extends z.ZodType>(data: T) =>
z.discriminatedUnion("success", [
z.object({ success: z.literal(true), data }),
z.object({ success: z.literal(false), error: z.object({ code: z.string(), message: z.string() }) }),
])
type Envelope<T> = { success: true; data: T } | { success: false; error: { code: string; message: string } }
function unwrap<T>(envelope: Envelope<T>, answer: AnswerHead): T {
if (envelope.success) return envelope.data
throw new HTTPError({ ...answer, data: envelope }, { message: envelope.error.message })
}
const User = z.object({ id: z.string(), name: z.string() })
const { endpoint } = courier()
const getUser = endpoint.get("users/:id").response(Envelope(User)).map(unwrap)
// caller.users.get({ id }) → Promise<{ id: string; name: string }>An envelope that says the call failed fails it. A direct caller's promise rejects with the HTTPError, its status the answer's own — 200 — and its data the envelope. A browser's call through the proxy is answered 502, as any answer the proxy could not use is, with the envelope as the error's data. A retry policy decides on it as on any HTTPError: a 200 is not retried.
One call per slot
.variables(), .response() and .send() each fill a slot, and a slot takes one schema or type: a second call would replace the first. It type-checks, but throws ConfigurationError("SLOT_ALREADY_SET") as soon as the module defining the endpoint loads, naming the slot and the endpoint:
endpoint.get(":id").response(UserSchema).response(AdminSchema)
// ConfigurationError: [courier] .response() was called twice on GET ":id". Each slot
// takes one schema or type, and the second would replace the first: remove one of the two calls.Endpoint settings
The same settings follow any head, in any order, and a base built with courier() or .extend() passes its own on to every endpoint made from it:
| method | what it sets |
|---|---|
.use(...middleware) | middleware for this endpoint, run after the base's |
.headers(names) | the headers it carries across the proxy, each way — see Headers |
.timeout(ms) | how long the upstream call may take |
.retry({ limit, delay, deadline, retryOn, mutations, … }) | its retry policy, in retryMiddleware's terms; a write is retried when it declares an idempotencyKey, when it never left, or with mutations: true. The policies of one API's endpoints share a retry budget |
.meta(values) | values for your own tooling; the runtime ignores them |
.cache({ revalidate, tags }) | how long a read's answer keeps — offered on a read alone |
.reads() | a read sent with a body, over POST; refused on .put(), .patch() and .del(). A write declared one loses what guards a write — see User Sessions |
.writes() | a write addressed with a reading verb — a GET that changes something, such as an unsubscribe link: sent once per call, its answer never kept, taken by the mutation hooks, and carried by the proxy as a POST while the upstream gets its own verb |
.cancelPrevious(cancel?) | whether a newer call of this read cancels its call still in flight — a search as the user types; false keeps every call whatever its group, client or API says. Offered on a read alone — see Deduplication & Abort |
.defaults(values) | what an HTTP endpoint sends for variables a call leaves out — see Default variables |
.map(stage) | what an HTTP endpoint's call resolves to, mapped from the answer its schema checked — see Mapping the answer |
.agent({ description, access }) | offers the endpoint to AI agents as a tool of your MCP server — named on an HTTP endpoint after its verb, and not passed on by a base; see MCP Server |
A verb also takes options for that endpoint alone — the header an idempotency key travels in, variables kept out of the address, skipping the base's middleware, and what Studio and the mock server read — each listed under A verb's options.
defineApi
Creates an API source by combining groups with a base URL and shared options:
import { defineApi } from "@noverax/courier/define"
import { users } from "./users"
import { posts } from "./posts"
const api = defineApi({
baseURL: process.env.API_URL!,
groups: { users, posts },
})
export const sources = { api }
export type Sources = typeof sourcesEndpoints in no group
An API holds endpoints of its own beside its groups — a health check, its root, anything no group is about — and the client calls them on itself:
import { courier, defineApi } from "@noverax/courier/define"
import { users } from "./users"
const { endpoint } = courier()
export const api = defineApi({
baseURL: process.env.API_URL!,
endpoints: {
health: endpoint.get("health"),
},
groups: { users },
})import { createCaller } from "@noverax/courier/server"
import { api } from "@/api/sources"
const caller = createCaller(api)
await caller.health()
await caller.users.getAll()An API may hold endpoints alone, with no group at all. Studio imports an operation with no tag this way, and a path no segment groups when grouping by path — see Import an API.
Options
defineApi accepts all BaseOptions:
defineApi({
baseURL: "https://api.example.com",
groups: { users, posts },
// Shared options for all endpoints in this source:
middleware: [retryMiddleware(), authMiddleware({ getToken: () => getToken() })],
timeout: 10000,
headers: { "X-API-Version": "2" },
responseType: "json", // "json" | "text" | "blob" | "arrayBuffer" | "formData"
defaultBody: { lang: "en" },
defaultQueryParams: { format: "json" },
})Multiple Sources
You can define multiple API sources for different backends:
const mainApi = defineApi({
baseURL: "https://api.example.com",
groups: { users, posts },
})
const authApi = defineApi({
baseURL: "https://auth.example.com",
groups: { auth },
})
export const sources = { mainApi, authApi }
export type Sources = typeof sourcesThen call them by name:
const mainCaller = createCaller(mainApi)
const authCaller = createCaller(authApi)
const users = await mainCaller.users.getAll()
const token = await authCaller.auth.login({ email, password })Dot-Notation Access
When calling endpoints, use dot-notation to access groups and methods:
caller.users.getAll() // group: "users", method: "getAll"
caller.users.getById(vars) // group: "users", method: "getById"
caller.posts.create(vars) // group: "posts", method: "create"
caller.billing.invoices.list() // group: "billing.invoices", method: "list"A group inside another is named by its path, its names joined with dots, wherever a group is named by a string: the proxy's _g, Studio, mocks, query keys and a page's routes.
Reserved names
options cannot name an endpoint, nor raw and with an endpoint or a group, nor __proto__ an endpoint, and no name holds a dot: each is refused with a ConfigurationError where the group or the source is defined. What each is kept for, and what a path of the same name may do, is under Reserved Names.
Names the runtime reads
The runtime reads then, toJSON and valueOf from any object. A group or endpoint you declare under one of these names is still reached by it, as long as the client knows the source — createCaller and createQueryCaller, and createProxyCaller and createProxyQueryCaller, which their routes tell what the source holds:
caller.files.toJSON() // the endpoint named toJSON
caller.then.list() // a group named then; the client is still not a promise
q.then.useQuery("list") // the same group through the React hooksOne name stays out of reach: a flat endpoint named then at the root. It would make every awaited client call it, so rename it. A proxy client whose routes name no member by one of these names answers it as absent.
Next Steps
- Caller & Proxy — how to call your endpoints
- Middleware — add retry, auth, logging to your API
- Validation — runtime schema validation