Course contentsShow
← TypeScript
Lesson 1585 of 1,79636. tRPC and End-to-End Type SafetyFree lesson

ts-rest Contract Structure

Defining ts-rest contracts with typed routes, parameters, and response shapes.

ts-rest Contract Structure

What you'll learn: How to define type-safe REST API contracts in ts-rest using typed routes, parameters, and response shapes.

The Contract as Single Source of Truth

With ts-rest, you define an API contract that serves as the shared agreement between client and server. Think of it as a blueprint that describes every endpoint's URL pattern, HTTP method, expected inputs, and response structure—all in TypeScript types.

Unlike traditional REST APIs where client and server types drift apart, ts-rest keeps both sides synchronized through a single contract definition.

Basic Contract Structure

A ts-rest contract uses the initContract() function to create a contract builder, then defines routes with explicit types:

import { initContract } from '@ts-rest/core';
import { z } from 'zod';

const c = initContract();

const postsContract = c.router({
  getPost: {
    method: 'GET',
    path: '/posts/:id',
    responses: {
      200: z.object({
        id: z.string(),
        title: z.string(),
        content: z.string(),
      }),
    },
  },
});

Each route specifies its method, path, and responses. The path can include parameters (:id), and responses are validated with Zod schemas.

Typed Request Parameters

You can type path parameters, query strings, and request bodies:

const usersContract = c.router({
  updateUser: {
    method: 'PATCH',
    path: '/users/:userId',
    body: z.object({
      name: z.string().optional(),
      email: z.string().email().optional(),
    }),
    responses: {
      200: z.object({
        userId: z.string(),
        name: z.string(),
        email: z.string(),
      }),
    },
  },
  
  searchUsers: {
    method: 'GET',
    path: '/users',
    query: z.object({
      q: z.string(),
      limit: z.number().optional(),
    }),
    responses: {
      200: z.array(z.object({
        userId: z.string(),
        name: z.string(),
      })),
    },
  },
});

The body field types request payloads, while query types URL query parameters. Path parameters are inferred from the :param syntax in the path string.

Multiple Response Codes

Contracts can define different response shapes for different HTTP status codes:

const authContract = c.router({
  login: {
    method: 'POST',
    path: '/auth/login',
    body: z.object({
      username: z.string(),
      password: z.string(),
    }),
    responses: {
      200: z.object({
        token: z.string(),
        expiresAt: z.string(),
      }),
      401: z.object({
        error: z.literal('Invalid credentials'),
      }),
      429: z.object({
        error: z.literal('Too many attempts'),
        retryAfter: z.number(),
      }),
    },
  },
});

Both client and server now understand which response shape corresponds to which status code—fully typed error handling across the wire.

Key takeaway: ts-rest contracts define your entire REST API in a single typed structure with explicit routes, parameters, bodies, queries, and response shapes, creating type safety from server implementation to client consumption without code generation.