HTTP Method Decorators
Decorators like @Get, @Post, @Put, @Patch, and @Delete map methods to HTTP verbs.
Syntax
@Post() / @HttpCode(status)Nest provides a decorator for each HTTP verb. Applying one to a method registers a route for that verb.
| Decorator | HTTP verb | Typical use |
|---|---|---|
@Get() | GET | Read data |
@Post() | POST | Create data |
@Put() | PUT | Replace data |
@Patch() | PATCH | Update part of data |
@Delete() | DELETE | Remove data |
By default Nest returns HTTP 200 for most handlers and 201 for @Post(). You can override this with @HttpCode().
Example
import { Controller, Get, Post, Delete, HttpCode } from '@nestjs/common';
@Controller('items')
export class ItemsController {
@Get()
findAll() { return 'list'; }
@Post()
create() { return 'created'; } // 201 by default
@Delete()
@HttpCode(204)
remove() { return; }
}When to use it
- A developer maps @Post to a create endpoint and @Delete(":id") to a remove endpoint for a CRUD users resource.
- An API uses @Patch(":id") instead of @Put(":id") because only partial updates are needed and the full resource replacement is not supported.
- A team uses @Options on a preflight route and @Head to let clients check resource availability without downloading the body.
More examples
CRUD with HTTP decorators
Puts all six standard CRUD HTTP method decorators in one controller for a clear side-by-side comparison.
import { Controller, Get, Post, Put, Patch, Delete, Param, Body } from '@nestjs/common';
@Controller('items')
export class ItemsController {
@Get() findAll() {}
@Get(':id') findOne(@Param('id') id: string) {}
@Post() create(@Body() dto: any) {}
@Put(':id') replace(@Param('id') id: string, @Body() dto: any) {}
@Patch(':id') update(@Param('id') id: string, @Body() dto: any) {}
@Delete(':id') remove(@Param('id') id: string) {}
}Custom status code on POST
Shows how @HttpCode overrides the default 201 status NestJS returns for POST routes to return 200 instead.
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
@Controller('auth')
export class AuthController {
@Post('login')
@HttpCode(HttpStatus.OK) // default POST returns 201; override to 200
login(@Body() dto: any) {
return { token: 'jwt...' };
}
}Patch for partial update
Demonstrates @Patch for partial resource updates, accepting only the fields provided in the request body.
import { Controller, Patch, Param, Body } from '@nestjs/common';
import { UpdateUserDto } from './dto/update-user.dto';
@Controller('users')
export class UsersController {
@Patch(':id')
update(
@Param('id') id: string,
@Body() updateUserDto: UpdateUserDto,
) {
return { id, ...updateUserDto };
}
}
Discussion