HTTP Methods
⭐ Interview Importance: LOW
⏱️ Revision Time: 7 min
HTTP Methods (or verbs) indicate the desired action to be performed on the identified resource.
Overview
NestJS provides decorators for all standard HTTP methods. These decorators are used to map a specific HTTP verb to a method inside a controller.
Following RESTful principles, you should use different HTTP methods to perform different operations (CRUD) on the same URL path.
Key Concepts
@Get(): Retrieve a resource. Should be idempotent and side-effect free.@Post(): Create a new resource. Not idempotent (calling it twice creates two resources).@Put(): Update an existing resource completely (replace it). Idempotent.@Patch(): Update an existing resource partially.@Delete(): Remove a resource. Idempotent.
Code Examples
A Complete RESTful Controller
import { Controller, Get, Post, Put, Patch, Delete, Body, Param } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
@Controller('users')
export class UsersController {
// 1. CREATE: POST /users
@Post()
create(@Body() createUserDto: CreateUserDto) {
return 'Creates a user';
}
// 2. READ ALL: GET /users
@Get()
findAll() {
return 'Returns all users';
}
// 3. READ ONE: GET /users/:id
@Get(':id')
findOne(@Param('id') id: string) {
return `Returns user #${id}`;
}
// 4. UPDATE (Partial): PATCH /users/:id
@Patch(':id')
updatePartial(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return `Updates specific fields of user #${id}`;
}
// 5. UPDATE (Full): PUT /users/:id
@Put(':id')
updateFull(@Param('id') id: string, @Body() createUserDto: CreateUserDto) {
return `Replaces user #${id} entirely`;
}
// 6. DELETE: DELETE /users/:id
@Delete(':id')
remove(@Param('id') id: string) {
return `Removes user #${id}`;
}
}
Best Practices
- Respect Idempotency: A
GET,PUT, orDELETErequest should be idempotent (making the exact same request 10 times should have the same effect on the server state as making it once).POSTrequests are generally not idempotent. - Use
PatchoverPut: In modern APIs,@Patch()is heavily favored over@Put(). It is rare that a client wants to replace an entire user object; usually, they just want to update a few fields like email or name. - Return 201 for POST: Nest does this automatically, but remember that a successful
POSTshould return201 Created, not200 OK.