Type-Safe REST with ts-rest
What you'll learn: How to define REST API contracts with ts-rest and automatically get type inference on both client and server sides without code generation.
The Problem ts-rest Solves
By this point, you've seen tRPC for RPC-style APIs and GraphQL with code generation. But what if you need traditional REST endpoints with full type safety? ts-rest lets you define a REST API contract once, then use it on both client and server with automatic inference—no build step required.
How ts-rest Works
You define your API contract as a TypeScript object describing routes, methods, request bodies, and responses. This contract becomes your single source of truth:
import { initContract } from '@ts-rest/core';
import { z } from 'zod';
const c = initContract();
const apiContract = c.router({
getUser: {
method: 'GET',
path: '/users/:id',
responses: {
200: z.object({
id: z.string(),
name: z.string(),
email: z.string(),
}),
},
},
createUser: {
method: 'POST',
path: '/users',
body: z.object({
name: z.string(),
email: z.string(),
}),
responses: {
201: z.object({
id: z.string(),
name: z.string(),
email: z.string(),
}),
},
},
});
Now both your server implementation and client calls get full type safety and autocomplete—the contract ensures they stay in sync without any code generation step.
Key Takeaway: ts-rest defines REST API contracts as TypeScript objects with Zod schemas, giving you automatic type inference on both client and server sides for traditional REST endpoints—combining the flexibility of REST with tRPC-like type safety.