0
0
NestJSframework~5 mins

Request body in NestJS

Choose your learning style9 modes available
Introduction

The request body holds data sent by a client to the server, often used to send information like form inputs or JSON data.

When a client submits a form with user details to create a new account.
When sending JSON data to update a user's profile information.
When uploading data like comments or messages to a server.
When an API client sends data to be processed or stored.
When you want to receive structured data from a client in a POST or PUT request.
Syntax
NestJS
import { Controller, Post, Body } from '@nestjs/common';

@Controller('example')
export class ExampleController {
  @Post()
  create(@Body() data: any) {
    return data;
  }
}

The @Body() decorator extracts the request body data.

You can type the data parameter to match the expected data shape.

Examples
This example shows how to type the request body to expect a name and age.
NestJS
import { Controller, Post, Body } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Post('create')
  createUser(@Body() userData: { name: string; age: number }) {
    return `User ${userData.name} is ${userData.age} years old.`;
  }
}
Here, the request body is expected to be a simple string message.
NestJS
import { Controller, Post, Body } from '@nestjs/common';

@Controller('messages')
export class MessagesController {
  @Post()
  saveMessage(@Body() message: string) {
    return `Message received: ${message}`;
  }
}
Sample Program

This controller handles POST requests to '/products/add'. It reads the product name and price from the request body and returns a confirmation string.

NestJS
import { Controller, Post, Body } from '@nestjs/common';

@Controller('products')
export class ProductsController {
  @Post('add')
  addProduct(@Body() product: { name: string; price: number }) {
    return `Added product: ${product.name} with price $${product.price}`;
  }
}
OutputSuccess
Important Notes

Always validate and sanitize request body data to keep your app safe.

Use DTOs (Data Transfer Objects) with classes and validation decorators for better structure.

Request body is usually used with POST, PUT, or PATCH HTTP methods.

Summary

The request body carries data sent from client to server.

Use @Body() decorator in NestJS to access this data.

Typing the body helps catch errors and improves code clarity.