Skip to content
rest-rpc
Esc
↑↓navigate↵open⌘Jpreview
On this page

Cheatsheet

Common rest-rpc patterns, each a complete example, with links to the documentation.

Type-safe REST APIs, for developers and agents. Write a route once, and it’s a validated HTTP endpoint, a typed client call, TanStack Query options, an OpenAPI operation and a tool for MCP servers and agent SDKs. Below are the common patterns, each a complete example. See the documentation for the rest, or llms.txt for agents.

Hello World

A route, an app and a typed client. The client here calls the app in the same process, which is also how to test it.

See Quickstart

import { createApp, createClient, route } from "@rest-rpc/server";

const router = {
	hello: route.get("/hello").handler(() => ({ message: "Hello" })),
};

const app = createApp(router); // `export default app` to serve it on Bun, Deno or Workers

const client = createClient(router, {
	origin: "http://localhost",
	fetch: app.fetch,
});
const { status, body } = await client.hello();
console.log(status, body.message); // 200 "Hello", typed from the handler

Methods and Paths

A route without a method is a POST, and without a path it’s at its keys in the route tree. :name segments are string params.

See Route Builder

import { route } from "@rest-rpc/server";
import * as z from "zod";

const base = route.prefix("/api");

export const router = {
	posts: {
		list: base
			.get("/posts")
			.handler(() => [{ id: "1", title: "Hello", body: "First post" }]), // GET /api/posts
		get: base.get("/posts/:id").handler(({ params }) => ({ id: params.id })), // params.id: string
		create: base
			.body(z.object({ title: z.string(), body: z.string() }))
			.handler(({ body }) => ({ id: "2", title: body.title, body: body.body })), // POST /api/posts/create
	},
};

Request Validation

Requests are validated before the handler runs, with any Standard Schema such as Zod, Valibot or ArkType. An invalid request gets a 400. Params, query and headers arrive as strings, so their schemas coerce.

See Validation

import { route } from "@rest-rpc/server";
import * as z from "zod";

const search = route
	.get("/users/:id/posts")
	.params(z.object({ id: z.coerce.number() }))
	.query(
		z.object({
			sort: z.enum(["new", "top"]).optional(),
			tags: z.array(z.string()).optional(),
		}),
	)
	.headers(z.object({ "x-request-id": z.string() }))
	.handler(({ params, query, headers }) => ({
		userId: params.id, // number
		sort: query.sort ?? "new",
		tags: query.tags ?? [], // sent as tags[]=a&tags[]=b
		requestId: headers["x-request-id"],
	}));

Status, Headers and Cookies

Return the body, or respond() to also set the status, headers or cookies.

See Responses

import { createApp, createClient, route } from "@rest-rpc/server";
import * as z from "zod";

const create = route
	.post("/posts")
	.body(z.object({ title: z.string(), body: z.string() }))
	.handler(({ body, respond }) => {
		const post = {
			id: crypto.randomUUID(),
			title: body.title,
			body: body.body,
		};
		return respond(post, {
			status: 201,
			headers: { location: `/posts/${post.id}` },
			cookies: ["draft=; Max-Age=0"],
		});
	});

const router = { create };

const app = createApp(router);
const client = createClient(router, {
	origin: "http://localhost",
	fetch: app.fetch,
});

const { status, headers } = await client.create({
	body: { title: "Hello", body: "First post" },
});
console.log(status, headers.location); // 201 "/posts/..."

Defined Responses

Without .response(), responses are inferred from the handler and not validated. Define them to validate them and document them in OpenAPI.

See Defined Responses

import { route } from "@rest-rpc/server";
import * as z from "zod";

const post = z.object({ id: z.string(), title: z.string(), body: z.string() });

const create = route
	.post("/posts")
	.body(z.object({ title: z.string(), body: z.string() }))
	.response(post, { status: 201 })
	.handler(({ body, respond }) =>
		respond({ id: crypto.randomUUID(), ...body }, { status: 201 }),
	);

Errors

Errors are thrown. An error the route defines is typed on the client, with its code and data.

See Errors

import {
	createApp,
	createClient,
	isDefinedError,
	route,
	safe,
} from "@rest-rpc/server";
import * as z from "zod";

const posts = new Map([["1", { id: "1", title: "Hello", body: "First post" }]]);

const router = {
	get: route
		.get("/posts/:id")
		.error("POST_NOT_FOUND", {
			status: 404,
			data: z.object({ id: z.string() }),
		})
		.handler(({ params, errors }) => {
			const post = posts.get(params.id);
			if (!post) throw errors.POST_NOT_FOUND({ data: { id: params.id } });
			return post;
		}),
};

const app = createApp(router);
const client = createClient(router, {
	origin: "http://localhost",
	fetch: app.fetch,
});

const { error, data } = await safe(client.get({ params: { id: "2" } }));
if (isDefinedError(error)) console.log(error.code, error.data.id); // "POST_NOT_FOUND" "2"
else if (error) throw error;
else console.log(data.body.title);

Shared Errors

routeError() defines an error once, to throw from any code and add to routes.

See Errors Outside Handlers

import { route, routeError } from "@rest-rpc/server";
import * as z from "zod";

const PostNotFound = routeError("POST_NOT_FOUND", {
	status: 404,
	data: z.object({ id: z.string() }),
});

const posts = new Map([["1", { id: "1", title: "Hello", body: "First post" }]]);

const findPost = (id: string) => {
	const post = posts.get(id);
	if (!post) throw new PostNotFound({ data: { id } });
	return post;
};

const get = route
	.get("/posts/:id")
	.error(PostNotFound)
	.handler(({ params }) => findPost(params.id));

Middleware, Context and Metadata

Middleware runs around the handler and passes it values through context. The server provides initial context, and metadata tells shared middleware about each route.

See Middleware and Context

import { createApp, route } from "@rest-rpc/server";

const base = route
	.$meta<{ access: "public" | "signed-in" }>()
	.$context<{ headers: Headers }>() // provided by the app below
	.error("UNAUTHORIZED", { status: 401 })
	.use(({ route, context, errors, next }) => {
		const user = context.headers.get("authorization");
		if (!user && route.meta?.access !== "public") throw errors.UNAUTHORIZED();
		return next({ context: { user } });
	});

const router = {
	health: base
		.get("/health")
		.meta({ access: "public" })
		.handler(() => "ok"),
	me: base
		.get("/me")
		.meta({ access: "signed-in" })
		.handler(({ context }) => context.user), // string | null
};

export default createApp(router, {
	context: (request) => ({ headers: request.headers }), // or an object, such as { db }
});

Server-Sent Events

Return an async iterable to stream events. The client iterates them.

See Server-Sent Events

import {
	createApp,
	createClient,
	route,
	sse,
	sseEvent,
} from "@rest-rpc/server";
import * as z from "zod";

const messages = ["Ada liked your post", "Grace commented on your post"];

const router = {
	notifications: route
		.get("/notifications")
		.response(sse(z.object({ message: z.string() }))) // optional, validates each event
		.handler(async function* ({ signal }) {
			for (const [i, message] of messages.entries()) {
				if (signal.aborted) break;
				yield sseEvent({ message }, { id: String(i) });
			}
		}),
};

const app = createApp(router);
const client = createClient(router, {
	origin: "http://localhost",
	fetch: app.fetch,
});

const { body } = await client.notifications();
for await (const event of body) console.log(event.id, event.data.message);

Content Types

A body is JSON unless its content-type header says otherwise. FormData is always sent as multipart/form-data, and a binary body arrives as a Blob.

See Content Types and Codecs

import { createApp, createClient, route } from "@rest-rpc/server";
import * as z from "zod";

const router = {
	upload: route
		.post("/upload")
		.body(z.instanceof(FormData))
		.handler(({ body, respond }) =>
			respond(`Got ${body.getAll("file").length} file(s)`, {
				headers: { "content-type": "text/plain" },
			}),
		),
};

const app = createApp(router);
const client = createClient(router, {
	origin: "http://localhost",
	fetch: app.fetch,
});

const form = new FormData();
form.set("file", new Blob(["Hello"]), "hello.txt");
const { body } = await client.upload({ body: form });
console.log(body); // "Got 1 file(s)"

Codecs

A codec sends another format, such as superjson to keep Date values. Pass the same codecs to the client and the server.

See Custom Codecs

import { bodyCodec, createApp, createClient, route } from "@rest-rpc/server";
import superjson from "superjson";

const superjsonCodec = bodyCodec("application/vnd.superjson+json", {
	serialize: (value) => superjson.stringify(value),
	deserialize: async (body) => superjson.parse(await body.text()),
});

const router = {
	post: route
		.get("/post")
		.handler(({ respond }) =>
			respond(
				{ title: "Hello", publishedAt: new Date() },
				{ headers: { "content-type": "application/vnd.superjson+json" } },
			),
		),
};

const bodyCodecs = [superjsonCodec];
const app = createApp(router, { bodyCodecs });
const client = createClient(router, {
	origin: "http://localhost",
	fetch: app.fetch,
	bodyCodecs,
});

const { body } = await client.post();
console.log(body.publishedAt instanceof Date); // true

Raw and Static Responses

Return a Fetch Response for what the builder can’t describe, such as a redirect. A response that never changes is .static(), built once at startup.

See Raw Responses

import { route } from "@rest-rpc/server";

const download = route
	.get("/images/:id")
	.handler(({ params }) =>
		Response.redirect(`https://cdn.example.com/${params.id}`, 302),
	);

const health = route.get("/health").static({ ok: true });

Interceptors

Interceptors run around every request, for app-wide work such as logging, API keys or CORS.

See Interceptors

import { createApp, interceptor, onError, route } from "@rest-rpc/server";

const logging = interceptor(async ({ request, next }) => {
	const response = await next();
	console.log(request.method, request.url, response.status);
	return response;
});

const router = { hello: route.get("/hello").handler(() => "Hello") };

export default createApp(router, {
	interceptors: [logging, onError((error) => console.error(error))],
});

Node

@rest-rpc/server/node serves the same routes with node:http.

See Serving Routes

import { createServer } from "node:http";
import { route } from "@rest-rpc/server";
import { createApp } from "@rest-rpc/server/node";

const router = { hello: route.get("/hello").handler(() => "Hello") };

createServer(createApp(router)).listen(3000);

Frameworks

Serve the same routes from any framework: under one of its routes, or each registered on its router.

See Framework Integration

import { Hono } from "hono";
import { createCatchAllHandler, route } from "@rest-rpc/server";

const router = { hello: route.get("/hello").handler(() => "Hello") };
const handler = createCatchAllHandler(router);

const app = new Hono();
app.all("/api/*", async (c) => {
	const result = await handler(c.req.raw, { mountPath: "/api" });
	return result.matched ? result.response : c.notFound();
});

export default app;

Browser Clients

A bundler macro runs extractContract() at build time, so the client gets the routes’ types without any server code. Bun runs macros itself, and Vite and other bundlers with unplugin-macros. The client sections below use these files.

See Contract Extraction

import { route } from "@rest-rpc/server";
import * as z from "zod";

const posts = new Map([["1", { id: "1", title: "Hello", body: "First post" }]]);

export const router = {
	posts: {
		list: route.get("/posts").handler(() => [...posts.values()]),
		get: route
			.get("/posts/:id")
			.error("POST_NOT_FOUND", { status: 404 })
			.handler(({ params, errors }) => {
				const post = posts.get(params.id);
				if (!post) throw errors.POST_NOT_FOUND();
				return post;
			}),
		create: route
			.body(z.object({ title: z.string(), body: z.string() }))
			.handler(({ body }) => {
				const post = { id: crypto.randomUUID(), ...body };
				posts.set(post.id, post);
				return post;
			}),
	},
};
import { extractContract } from "@rest-rpc/core";
import { router } from "./router.ts";

export function getContract() {
	return extractContract(router);
}
import { createClient } from "@rest-rpc/core";
import { getContract } from "./contract.ts" with { type: "macro" };

export const client = createClient(getContract()); // the page's origin, or pass { origin }
import Macros from "unplugin-macros/vite";
import { defineConfig } from "vite";

export default defineConfig({ plugins: [Macros()] });

Client Options

Headers for every request, the server’s mount path, and interceptors around each request.

See Fetch Client

import { clientInterceptor, createClient } from "@rest-rpc/core";
import { getContract } from "./contract.ts" with { type: "macro" };

const logging = clientInterceptor(async ({ request, next }) => {
	const response = await next();
	console.log(request.method, request.url, response.status);
	return response;
});

export const client = createClient(getContract(), {
	origin: "https://api.example.com",
	mountPath: "/api",
	globalHeaders: {
		authorization: () => `Bearer ${localStorage.getItem("token")}`,
	},
	interceptors: [logging],
});

TanStack Query

Query and mutation options for each route, with typed keys. fetch() calls a route directly, such as in a router loader.

See TanStack Query

import { createClient } from "@rest-rpc/core";
import { createTanstackQueryUtils } from "@rest-rpc/tanstack-query";
import { getContract } from "./contract.ts" with { type: "macro" };

export const client = createClient(getContract());
export const queryUtils = createTanstackQueryUtils(client);
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { queryUtils } from "./client";

export function Posts() {
	const queryClient = useQueryClient();
	const posts = useQuery(
		queryUtils.posts.list.queryOptions({ select: (response) => response.body }),
	);
	const create = useMutation(
		queryUtils.posts.create.mutationOptions({
			onSuccess: () =>
				queryClient.invalidateQueries({
					queryKey: queryUtils.posts.list.key(),
				}),
		}),
	);
	return (
		<button
			onClick={() =>
				create.mutate({ body: { title: "Hello", body: "First post" } })
			}
		>
			{posts.data?.length ?? 0} posts
		</button>
	);
}
import { queryUtils } from "./client";

export async function loadPost(id: string) {
	const { body: post } = await queryUtils.posts.get.fetch({ params: { id } });
	return post;
}

Contract-first

Define routes in a contract with @rest-rpc/core, and implement them on the server. The client imports the contract directly.

See Contract-first

import { route } from "@rest-rpc/core";
import * as z from "zod";

export const contract = {
	posts: {
		get: route
			.get("/posts/:id")
			.response(
				z.object({ id: z.string(), title: z.string(), body: z.string() }),
			)
			.error("POST_NOT_FOUND", { status: 404 }),
	},
};
import { createApp, implement } from "@rest-rpc/server";
import { contract } from "./contract.ts";

const router = {
	posts: {
		get: implement(contract.posts.get).handler(({ params }) => ({
			id: params.id,
			title: "Hello",
			body: "First post",
		})),
	},
};

export default createApp(router);
import { createClient } from "@rest-rpc/core";
import { contract } from "./contract";

export const client = createClient(contract, { validateResponses: true });

Local Calls

call() runs one route with its validation and middleware, without HTTP. To test the whole app, pass app.fetch to the client as in Hello World.

See Local Calls

import { call, route } from "@rest-rpc/server";
import * as z from "zod";

const double = route
	.get("/double/:n")
	.params(z.object({ n: z.coerce.number() }))
	.handler(({ params }) => params.n * 2);

const { body } = await call(double, { params: { n: 21 } });
console.log(body); // 42

OpenAPI

Generate an OpenAPI document from the routes, with a converter for your schema library.

See OpenAPI

import { createOpenApiDocument, route } from "@rest-rpc/server";
import * as z from "zod";

const router = {
	posts: {
		list: route
			.get("/posts")
			.response(
				z.array(
					z.object({ id: z.string(), title: z.string(), body: z.string() }),
				),
			)
			.openAPI({ summary: "List posts", tags: ["Posts"] })
			.handler(() => [{ id: "1", title: "Hello", body: "First post" }]),
	},
};

const document = createOpenApiDocument(router, {
	info: { title: "Blog API", version: "1.0.0" },
	schemaConverter: (schema, io) => z.toJSONSchema(schema as z.ZodType, { io }),
});

MCP Tools

createToolsFromRoutes() turns routes into tools for an MCP server or an agent SDK. Each call runs the route with its validation and middleware.

See MCP Tools

import {
	createMcpHandler,
	fromJsonSchema,
	McpServer,
} from "@modelcontextprotocol/server";
import { createApp, createToolsFromRoutes, route } from "@rest-rpc/server";
import * as z from "zod";

const posts = [{ id: "1", title: "Hello", body: "First post" }];

const router = {
	posts: {
		search: route
			.get("/posts/search")
			.query(z.object({ text: z.string().describe("Words to find in posts") }))
			.openAPI({ summary: "Search posts by their title and body" })
			.handler(({ query }) =>
				posts.filter(({ title, body }) =>
					`${title} ${body}`.includes(query.text),
				),
			),
	},
};

const tools = createToolsFromRoutes(router, {
	schemaConverter: (schema, io) => z.toJSONSchema(schema as z.ZodType, { io }),
});

const mcp = createMcpHandler(() => {
	const server = new McpServer({ name: "blog", version: "1.0.0" });
	for (const { definition, call } of tools) {
		const { name, inputSchema, outputSchema, ...config } = definition;
		server.registerTool(
			name,
			{
				...config,
				inputSchema: fromJsonSchema<Record<string, unknown>>(inputSchema),
				...(outputSchema && { outputSchema: fromJsonSchema(outputSchema) }),
			},
			(args) => call(args),
		);
	}
	return server;
});

const app = createApp(router);

export default {
	fetch: (request: Request) =>
		new URL(request.url).pathname === "/mcp"
			? mcp.fetch(request)
			: app.fetch(request),
};

Type Helpers

Reuse a route’s types outside it, such as in a handler written apart from its route.

See Type Helpers

import type { InferClientResponse } from "@rest-rpc/core";
import { route, type InferServerRequest } from "@rest-rpc/server";
import * as z from "zod";

const updateDefinition = route
	.patch("/posts/:id")
	.body(z.object({ title: z.string(), body: z.string() }));

const updatePost = ({
	params,
	body,
}: InferServerRequest<typeof updateDefinition>) => ({
	id: params.id,
	title: body.title,
	body: body.body,
});

const router = { posts: { update: updateDefinition.handler(updatePost) } };

type UpdateResponse = InferClientResponse<typeof router.posts.update>; // { status: 200; body: { id; title; body }; ... }

Was this page helpful?