Menu
CoddyTech

DTOs

Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 13 of 24.

@Body() body: { title: string } describes the body in one place only, and nothing checks it: { "title": 42 } goes straight through. A DTO, a data transfer object, is a class that describes what a request body holds.

export class CreateOrderDto {
    customer: string;
    express?: boolean;
}

@Post()
create(@Body() dto: CreateOrderDto) {
    return this.ordersService.create(dto);
}

express? marks an optional field. The controller and the service share the class, so they agree on the shape.

A DTO is a class, not an interface, for a reason. Interfaces are removed with the other types when the code runs, while a class still exists. Nest's validation reads rules written as decorators, and decorators need a class. That is the next lesson.

challenge icon

Challenge

Easy

Clients may now create a task that is already done. Describe the body of POST /tasks with a DTO, a class that lists the fields a request body holds, and pass it all the way to the service.

  1. In src/tasks/dto/create-task.dto.ts, give the class CreateTaskDto two fields: title, a string, and done, an optional boolean.
  2. In src/tasks/tasks.controller.ts, change the create method. Its @Body() parameter now has the type CreateTaskDto instead of { title: string }. Pass the whole DTO to the service, not only the title.
  3. In src/tasks/tasks.service.ts, change create to take the DTO instead of a title. The new task gets its title from the DTO, and its done from the DTO too, or false when the body has no done. The id and createdAt work as before.

Try it: POST { "title": "Pay rent", "done": true } to /tasks. You get 201 and the new task, finished:

{ "id": 4, "title": "Pay rent", "done": true, "createdAt": "2026-10-30T09:15:00.000Z" }

(createdAt shows the time of your request.) POST { "title": "Buy milk" }: 201 with "done": false. Then POST { "title": 42 }. You still get 201, with "title": 42 saved: the DTO describes the body but checks nothing yet. The next lesson makes Nest refuse it.

Try it yourself

// Describe the body of POST /tasks: a title, and done when the client sends it.
export class CreateTaskDto {}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in TypeScript and NestJS

Practice on your own: Express playground