---
title: Type-safe REST APIs, for developers and agents.
description: 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.
sidebar:
  label: Introduction
---

Types connect all of it, so the compiler shows what a change breaks before
anything runs. See [Type Safety](/docs/design/type-safety).

## One Route, Every Consumer

**Routes**

```ts twoslash
// ---cut-start---
// @filename: router.ts
import { respond, route } from "@rest-rpc/server";
import * as z from "zod";

declare function createPost(
	title: string,
	body: string,
): { id: string; title: string; body: string };
declare function findPost(
	id: string,
): { id: string; title: string; body: string } | undefined;
// ---cut-end---
// POST /posts/create, JSON body, 200 result.
const create = route
	.body(z.object({ title: z.string(), body: z.string() }))
	.handler(({ body: { title, body } }) => createPost(title, body));

// GET /posts/:id with params, query, headers, an error, and response headers.
const get = route
	.get("/posts/:id")
	.params(z.object({ id: z.string() }))
	.query(z.object({ preview: z.enum(["true", "false"]).optional() }))
	.headers(z.object({ "x-request-id": z.string().optional() }))
	.error("POST_NOT_FOUND", { status: 404 })
	.handler(({ params, query, errors }) => {
		const post = findPost(params.id);
		if (!post) throw errors.POST_NOT_FOUND();
		return respond(
			{
				...post,
				body: query.preview === "true" ? post.body.slice(0, 40) : post.body,
			},
			{ headers: { "x-powered-by": "rest-rpc" } },
		);
	});

export const router = { posts: { create, get } };
```

**Client**

```ts twoslash
// ---cut-start---
// @allowImportingTsExtensions
// @noEmit
// @filename: router.ts
import { respond, route } from "@rest-rpc/server";
import * as z from "zod";

declare function createPost(
	title: string,
	body: string,
): { id: string; title: string; body: string };
declare function findPost(
	id: string,
): { id: string; title: string; body: string } | undefined;

// POST /posts/create, JSON body, 200 result.
const create = route
	.body(z.object({ title: z.string(), body: z.string() }))
	.handler(({ body: { title, body } }) => createPost(title, body));

// GET /posts/:id with params, query, headers, an error, and response headers.
const get = route
	.get("/posts/:id")
	.params(z.object({ id: z.string() }))
	.query(z.object({ preview: z.enum(["true", "false"]).optional() }))
	.headers(z.object({ "x-request-id": z.string().optional() }))
	.error("POST_NOT_FOUND", { status: 404 })
	.handler(({ params, query, errors }) => {
		const post = findPost(params.id);
		if (!post) throw errors.POST_NOT_FOUND();
		return respond(
			{
				...post,
				body: query.preview === "true" ? post.body.slice(0, 40) : post.body,
			},
			{ headers: { "x-powered-by": "rest-rpc" } },
		);
	});

export const router = { posts: { create, get } };

// @filename: contract.ts
import type { router } from "./router";
export declare function getContract(): typeof router;

// @filename: client.ts
// ---cut-end---
import { createClient } from "@rest-rpc/core";
// getContract() runs extractContract(router) at build time.
import { getContract } from "./contract.ts" with { type: "macro" };

const client = createClient(getContract(), { origin: "http://localhost:3000" });

const created = await client.posts.create({
	body: { title: "Hello", body: "First post" },
});
const response = await client.posts.get({
	params: { id: created.body.id },
	query: { preview: "true" },
	headers: { "x-request-id": "req_1" },
});

if (response.status === 200) {
	console.log(response.body.title);
}
```

**TanStack Query**

```tsx twoslash
// ---cut-start---
// @allowImportingTsExtensions
// @noEmit
// @filename: router.ts
import { respond, route } from "@rest-rpc/server";
import * as z from "zod";

declare function createPost(
	title: string,
	body: string,
): { id: string; title: string; body: string };
declare function findPost(
	id: string,
): { id: string; title: string; body: string } | undefined;

// POST /posts/create, JSON body, 200 result.
const create = route
	.body(z.object({ title: z.string(), body: z.string() }))
	.handler(({ body: { title, body } }) => createPost(title, body));

// GET /posts/:id with params, query, headers, an error, and response headers.
const get = route
	.get("/posts/:id")
	.params(z.object({ id: z.string() }))
	.query(z.object({ preview: z.enum(["true", "false"]).optional() }))
	.headers(z.object({ "x-request-id": z.string().optional() }))
	.error("POST_NOT_FOUND", { status: 404 })
	.handler(({ params, query, errors }) => {
		const post = findPost(params.id);
		if (!post) throw errors.POST_NOT_FOUND();
		return respond(
			{
				...post,
				body: query.preview === "true" ? post.body.slice(0, 40) : post.body,
			},
			{ headers: { "x-powered-by": "rest-rpc" } },
		);
	});

export const router = { posts: { create, get } };

// @filename: contract.ts
import type { router } from "./router";
export declare function getContract(): typeof router;

// @filename: client.tsx
import { getContract } from "./contract.ts" with { type: "macro" };
// ---cut-end---
import { createClient } from "@rest-rpc/core";
import { createTanstackQueryUtils } from "@rest-rpc/tanstack-query";
import { useQuery, useMutation } from "@tanstack/react-query";

const queryUtils = createTanstackQueryUtils(
	createClient(getContract(), { origin: "http://localhost:3000" }),
);

const post = useQuery(
	queryUtils.posts.get.queryOptions({
		request: {
			params: { id: "post_1" },
			query: { preview: "true" },
		},
	}),
);
const create = useMutation(queryUtils.posts.create.mutationOptions());

create.mutate({ body: { title: "Hello", body: "First post" } });
```

**MCP and Agent SDK Tools**

```ts twoslash
// ---cut-start---
// @allowImportingTsExtensions
// @noEmit
// @filename: router.ts
import { respond, route } from "@rest-rpc/server";
import * as z from "zod";

declare function createPost(
	title: string,
	body: string,
): { id: string; title: string; body: string };
declare function findPost(
	id: string,
): { id: string; title: string; body: string } | undefined;

// POST /posts/create, JSON body, 200 result.
const create = route
	.body(z.object({ title: z.string(), body: z.string() }))
	.handler(({ body: { title, body } }) => createPost(title, body));

// GET /posts/:id with params, query, headers, an error, and response headers.
const get = route
	.get("/posts/:id")
	.params(z.object({ id: z.string() }))
	.query(z.object({ preview: z.enum(["true", "false"]).optional() }))
	.headers(z.object({ "x-request-id": z.string().optional() }))
	.error("POST_NOT_FOUND", { status: 404 })
	.handler(({ params, query, errors }) => {
		const post = findPost(params.id);
		if (!post) throw errors.POST_NOT_FOUND();
		return respond(
			{
				...post,
				body: query.preview === "true" ? post.body.slice(0, 40) : post.body,
			},
			{ headers: { "x-powered-by": "rest-rpc" } },
		);
	});

export const router = { posts: { create, get } };

// @filename: tools.ts
// ---cut-end---
import { createToolsFromRoutes } from "@rest-rpc/server";
import * as z from "zod";
import { router } from "./router.ts";

// posts_create and posts_get, to register on an MCP server or an agent SDK.
export const tools = createToolsFromRoutes(router, {
	schemaConverter: (schema, io) => z.toJSONSchema(schema as z.ZodType, { io }),
});
```

**HTTP**

```http wrap
# No method or path defined: POST, at the path of the route's keys.
POST /posts/create HTTP/1.1
Content-Type: application/json

{ "title": "Hello", "body": "Routes return data and clients call them like functions." }
```

```http wrap
HTTP/1.1 200 OK
Content-Type: application/json

{ "id": "post_1", "title": "Hello", "body": "Routes return data and clients call them like functions." }
```

```http wrap
GET /posts/post_1?preview=true HTTP/1.1
X-Request-Id: req_1
```

```http wrap
HTTP/1.1 200 OK
Content-Type: application/json
X-Powered-By: rest-rpc

{ "id": "post_1", "title": "Hello", "body": "Routes return data and clients call them" }
```

```http wrap
# A defined error is sent as JSON with its status.
GET /posts/missing HTTP/1.1
```

```http wrap
HTTP/1.1 404 Not Found
Content-Type: application/json

{ "code": "POST_NOT_FOUND", "message": "POST_NOT_FOUND" }
```

## Mistakes Fail to Compile

A request that doesn't match the route or a read of a field it doesn't return
is a type error, in every client of the route:

```ts twoslash
// @errors: 2353 2551
// ---cut-start---
// @allowImportingTsExtensions
// @noEmit
// @filename: router.ts
import { respond, route } from "@rest-rpc/server";
import * as z from "zod";

declare function createPost(
	title: string,
	body: string,
): { id: string; title: string; body: string };
declare function findPost(
	id: string,
): { id: string; title: string; body: string } | undefined;

// POST /posts/create, JSON body, 200 result.
const create = route
	.body(z.object({ title: z.string(), body: z.string() }))
	.handler(({ body: { title, body } }) => createPost(title, body));

// GET /posts/:id with params, query, headers, an error, and response headers.
const get = route
	.get("/posts/:id")
	.params(z.object({ id: z.string() }))
	.query(z.object({ preview: z.enum(["true", "false"]).optional() }))
	.headers(z.object({ "x-request-id": z.string().optional() }))
	.error("POST_NOT_FOUND", { status: 404 })
	.handler(({ params, query, errors }) => {
		const post = findPost(params.id);
		if (!post) throw errors.POST_NOT_FOUND();
		return respond(
			{
				...post,
				body: query.preview === "true" ? post.body.slice(0, 40) : post.body,
			},
			{ headers: { "x-powered-by": "rest-rpc" } },
		);
	});

export const router = { posts: { create, get } };

// @filename: contract.ts
import type { router } from "./router";
export declare function getContract(): typeof router;

// @filename: client.ts
import { createClient } from "@rest-rpc/core";
import { getContract } from "./contract.ts" with { type: "macro" };
const client = createClient(getContract(), { origin: "http://localhost:3000" });
// ---cut-end---
const response = await client.posts.get({ params: { postId: "post_1" } });

if (response.status === 200) {
	console.log(response.body.titel);
}
```

Rename a field the handler returns, and every client and query that reads it
stops compiling until it's updated. For a coding agent, `tsc` is the check
that its change is complete.

## Write Shared Logic Once

A builder holds what a group of routes shares, such as context, errors and
middleware. Every route built from it inherits them, typed:

```ts
const authenticated = route
	.$context<{ headers: Headers }>()
	.error("UNAUTHORIZED", { status: 401 })
	.use(({ context, errors, next }) => {
		const user = context.headers.get("authorization");
		if (!user) throw errors.UNAUTHORIZED();
		return next({ context: { user } });
	});

const router = {
	me: authenticated.get("/me").handler(({ context }) => context.user),
	posts: {
		create: authenticated
			.body(z.object({ title: z.string(), body: z.string() }))
			.handler(({ body, context }) => createPost(context.user, body)),
	},
};
```

## Fits What You Have

- **Just HTTP**: methods, paths, query, headers, statuses and content types
  are what they look like. Any HTTP client can call the routes.
- **Any runtime**: Bun, Deno, Cloudflare Workers and Node.
- **Any framework or none**: serve routes with `createApp`, or from Hono,
  Express, Fastify and others. Routes are the same either way.
- **Any schema library**: Zod, Valibot, ArkType or any Standard Schema.
- **Primitives over features**: authentication, caching and dependency
  injection are a few lines of middleware and context, written your way,
  instead of built-in features to configure.

## Get Started

**[Quickstart](/docs/quickstart/)**

Define routes and call them from a typed client.

**[Route Builder](/docs/route-builder/)**

Requests, responses, errors and streams.

**[MCP Tools](/docs/tooling/mcp-tools/)**

Serve the same routes to agents.

**[OpenAPI](/docs/tooling/openapi/)**

Generate an OpenAPI document from your routes.

For coding agents, install the `rest-rpc` skill. It points them to the
cheatsheet that ships with each package:

```package-install
npx skills add simoalanne/rest-rpc
```

## Common Questions

**Do I have to restructure my app?**

No. Keep your authentication, database access and deployment, and your
framework if you have one. Add typed routes at the API boundary, and adopt
the client, TanStack Query, OpenAPI, or MCP server and agent SDK tools when
they're useful.

**Do I need a server framework?**

No, any framework or none works. `createApp` serves routes without one, and
any framework can serve them instead. Routes don't change, so you can switch
later.

**Can I have a separate contract?**

Yes. Define the interface on its own, implement it on the server, and share
it with clients. See [Contract-first](/docs/contract-first/).

**What makes it good for coding agents?**

A type check shows whether a change is complete, and the API has one obvious
way to do each thing, so generated code looks like the docs. The skill, the
cheatsheet and llms.txt give agents the docs of the installed version.
