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

Defining zodios API Contracts

Writing zodios endpoint definitions with Zod schemas for requests and responses.

Defining zodios API Contracts

What you'll learn: How to write zodios endpoint definitions that combine Zod schemas with HTTP metadata for type-safe REST APIs.

What Are zodios API Contracts?

In zodios, an API contract is a plain TypeScript array that describes your REST endpoints. Each endpoint definition includes:

  • The HTTP method (GET, POST, etc.)
  • The URL path with optional parameters
  • Zod schemas for request bodies, query parameters, and responses

Think of it like writing an OpenAPI specification, but entirely in TypeScript with runtime validation built-in. The contract becomes your single source of truth — zodios uses it to generate types and validate data at runtime.

The Anatomy of an Endpoint Definition

Each endpoint in your contract is an object with these key properties:

  • method: HTTP verb as a string literal ("get", "post", "put", "delete", etc.)
  • path: URL path string, with :param syntax for path parameters
  • response: Zod schema defining the successful response shape
  • parameters (optional): Array of parameter definitions with Zod schemas
  • description (optional): Human-readable endpoint description

The beauty is that zodios infers TypeScript types from these Zod schemas, giving you autocomplete and type safety without writing types twice.

A Basic Contract Example

import { z } from "zod";

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
});

const apiContract = [
  {
    method: "get",
    path: "/users/:id",
    response: userSchema,
  },
  {
    method: "post",
    path: "/users",
    parameters: [
      {
        name: "body",
        type: "Body",
        schema: userSchema.omit({ id: true }),
      },
    ],
    response: userSchema,
  },
] as const;

Notice the as const assertion — it preserves literal types so zodios can infer exact method names and paths.

Key Takeaway: zodios API contracts merge Zod's runtime validation with HTTP metadata, creating a single definition that generates both types and runtime checks for your REST endpoints.