Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Creating and Using DTOs | Working with Data
Building Backend Applications with Nest.js

bookCreating and Using DTOs

Swipe um das Menü anzuzeigen

Create a new file in the src folder:

create-user.dto.ts

Add the following code:

export class CreateUserDto {
  name: string;
  age: number;
}

This DTO defines the structure of the data your application expects.

Now use it in your controller:

import { Controller, Post, Body } from '@nestjs/common';
import { CreateUserDto } from './create-user.dto';

@Controller('users')
export class UsersController {
  @Post()
  createUser(@Body() body: CreateUserDto) {
    return body;
  }
}

Here is what is happening:

  • CreateUserDto: defines required fields;
  • @Body(): extracts request data;
  • CreateUserDto: ensures the data follows the defined structure.

Now send a request with data:

{
  "name": "Alice",
  "age": 30
}

The controller receives structured data based on the DTO.

Using DTOs keeps your data consistent and avoids repeating type definitions across your application.

question mark

Where is a DTO typically used in Nest.js?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 5. Kapitel 3

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 5. Kapitel 3
some-alt