Request Body and Headers

@Body and @Headers

@Body() gives you the parsed JSON body (usually typed with a DTO class, covered in the DTOs module). @Headers('name') reads one header.

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

export class CreateProductDto {
  name: string;
  price: number;
  stock: number;
  category: string;
}

@Controller('products')
export class ProductsController {
  @Post()
  create(@Body() dto: CreateProductDto, @Headers('x-request-id') requestId?: string) {
    return { received: dto, requestId: requestId ?? null };
  }
}

Example

curl -X POST http://localhost:3000/products \
  -H "Content-Type: application/json" -H "x-request-id: req-101" \
  -d '{"name":"Mi Power Bank 20000","price":1899,"stock":75,"category":"accessories"}'

Example output

{"received":{"name":"Mi Power Bank 20000","price":1899,"stock":75,"category":"accessories"},"requestId":"req-101"}

Other Parameter Decorators

DecoratorGives you
@Body('name')One property of the body
@Query()The whole query object
@Param()All path params as an object
@Ip()Client IP address
@Req() / @Res()Raw Express request / response (avoid unless needed)

Note: If you inject @Res(), NestJS stops sending the response for you; you must call res.json() yourself. Use @Res({ passthrough: true }) if you only want to set a cookie or header.