Course contentsShow
← TypeScript
Lesson 1279 of 1,79630. Type-Safe APIsFree lesson

Request Body Typing

Typing POST/PUT/PATCH request bodies to ensure you send the correct shape to your API endpoints.

Request Body Typing

What you'll learn: How to ensure your POST, PUT, and PATCH requests send the correct data shape to your API endpoints.

When you send data to an API endpoint that modifies or creates resources, that data goes in the request body. Without proper typing, you might send the wrong fields, misspell property names, or pass incorrect value types—errors that only surface at runtime when the API rejects your request.

Why Request Body Typing Matters

Think of your API like a form at the DMV. If you show up with the wrong paperwork or missing fields, they'll reject your application. Request body typing is like having a checklist before you go, ensuring you have everything the API expects.

TypeScript lets you define interfaces or type aliases that represent the exact shape of data your endpoint requires. When you construct that request body, the compiler validates you're sending the right structure.

Typing Request Bodies

interface CreateUserRequest {
  email: string;
  password: string;
  age?: number;
}

async function createUser(userData: CreateUserRequest) {
  const response = await fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userData)
  });
  return response;
}

// ✓ Valid
createUser({ email: 'user@example.com', password: 'secret123' });

// ✗ Error: missing required 'password' property
createUser({ email: 'user@example.com' });

// ✗ Error: 'age' should be number, not string
createUser({ email: 'user@example.com', password: 'secret', age: 'thirty' });

Notice how the userData parameter is typed as CreateUserRequest. This means before the data even reaches JSON.stringify, TypeScript has verified it matches the contract.

Different Bodies for Different Methods

interface CreateProductRequest {
  name: string;
  price: number;
  categoryId: string;
}

interface UpdateProductRequest {
  name?: string;
  price?: number;
  categoryId?: string;
}

async function createProduct(data: CreateProductRequest) {
  return fetch('/api/products', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

async function updateProduct(id: string, data: UpdateProductRequest) {
  return fetch(`/api/products/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

POST endpoints often require all fields (creating a new resource), while PATCH endpoints accept partial updates. By typing them separately, you catch mistakes like forgetting required fields on creation or sending unexpected data on updates.

Reusing Types with Utility Types

interface Product {
  id: string;
  name: string;
  price: number;
  createdAt: Date;
}

type CreateProductRequest = Omit<Product, 'id' | 'createdAt'>;
type UpdateProductRequest = Partial<Omit<Product, 'id' | 'createdAt'>>;

Here we derive request types from the full Product type: creation omits server-generated fields, and updates make all remaining fields optional.

Key Takeaway: Typing request bodies prevents sending malformed data to your API by enforcing the correct property names, types, and required fields at compile time—catching errors before they become failed HTTP requests.