A Data Transfer Object (DTO) is a class that defines the shape of data sent over the network, such as a request body. Nest recommends classes over TypeScript interfaces. Interfaces are removed at compile time, and pipes need a real class at runtime.
export class CreateUserDto {
@IsString()
@IsNotEmpty()
name: string;
@IsEmail()
email: string;
@IsInt()
@Min(18)
age: number;
}
@Post()
createUser(@Body() createUserDto: CreateUserDto) {
return this.userService.create(createUserDto);
}
The class-validator decorators only describe the rules. They run when ValidationPipe is active, usually registered once with app.useGlobalPipes(new ValidationPipe()). An invalid body then gets a 400 Bad Request response before the handler runs.
DTOs give you type safety in the handler, input validation and a clear data contract. @nestjs/swagger also reads DTO classes to generate API documentation.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓