Route handlers let your app respond to different web requests like getting data or sending new info. They help your app talk to users or other apps.
Route handlers (GET, POST, PUT, DELETE) in NestJS
Introduction
Syntax
NestJS
@Get('path') @Post('path') @Put('path') @Delete('path') methodName() { // code to handle request }
Each decorator (@Get, @Post, etc.) matches an HTTP method.
The 'path' is the URL part that triggers this handler.
Examples
NestJS
@Get('users') getUsers() { return 'List of users'; }
NestJS
@Post('users') createUser() { return 'User created'; }
NestJS
@Put('users/:id') updateUser() { return 'User updated'; }
NestJS
@Delete('users/:id') deleteUser() { return 'User deleted'; }
Sample Program
This controller manages a list of items with GET, POST, PUT, and DELETE routes. It shows how to get all items, add a new one, update by ID, and delete by ID.
NestJS
import { Controller, Get, Post, Put, Delete, Param, Body } from '@nestjs/common'; @Controller('items') export class ItemsController { private items = [{ id: 1, name: 'Book' }]; @Get() getAll() { return this.items; } @Post() addItem(@Body() newItem: { name: string }) { const id = this.items.length + 1; const item = { id, name: newItem.name }; this.items.push(item); return item; } @Put(':id') updateItem(@Param('id') id: string, @Body() update: { name: string }) { const item = this.items.find(i => i.id === +id); if (item) { item.name = update.name; return item; } return { message: 'Item not found' }; } @Delete(':id') deleteItem(@Param('id') id: string) { const index = this.items.findIndex(i => i.id === +id); if (index !== -1) { const deleted = this.items.splice(index, 1); return deleted[0]; } return { message: 'Item not found' }; } }
Important Notes
Use @Param to get URL parts like IDs.
Use @Body to get data sent by the client in POST or PUT.
Route paths can have variables like ':id' to handle specific items.
Summary
Route handlers respond to different HTTP methods to manage data.
Use decorators like @Get, @Post, @Put, and @Delete to define routes.
Parameters and body data help customize what the handler does.
Practice
1. Which decorator is used in NestJS to create a route handler that responds to HTTP GET requests?
easy
Solution
Step 1: Understand HTTP methods and their decorators
In NestJS, each HTTP method has a specific decorator: @Get for GET, @Post for POST, @Put for PUT, and @Delete for DELETE.Step 2: Match the decorator to the GET method
The decorator @Get is specifically designed to handle HTTP GET requests.Final Answer:
@Get -> Option AQuick Check:
GET method uses @Get decorator [OK]
Hint: GET requests use @Get decorator in NestJS [OK]
Common Mistakes:
- Confusing @Post or @Put with @Get
- Using @Delete for GET requests
- Not using any decorator
2. Which of the following is the correct syntax to define a POST route handler in a NestJS controller?
easy
Solution
Step 1: Check the decorator syntax
Decorators in NestJS start with '@' and are case-sensitive. The correct decorator for POST is '@Post'.Step 2: Verify the route path and method name
The route path '/create' is correctly passed as a string argument, and the method name is valid.Final Answer:
@Post('/create') createItem() {} -> Option AQuick Check:
Correct decorator syntax uses '@Post' with parentheses [OK]
Hint: Decorators start with '@' and are case-sensitive [OK]
Common Mistakes:
- Missing '@' before decorator
- Using lowercase '@post' instead of '@Post'
- Using wrong decorator like '@Put' for POST
3. Given the following NestJS controller code, what will be the HTTP method and route path to access the handler?
@Controller('users')
export class UserController {
@Put(':id')
updateUser() {
return 'User updated';
}
}medium
Solution
Step 1: Identify the controller base path
The @Controller('users') decorator sets the base route path to '/users'.Step 2: Identify the route handler method and path
The @Put(':id') decorator means this handler responds to HTTP PUT requests at the path '/users/:id', where ':id' is a route parameter.Final Answer:
PUT /users/:id -> Option CQuick Check:
@Put with ':id' means PUT method at /users/:id [OK]
Hint: Decorator @Put means HTTP PUT method [OK]
Common Mistakes:
- Confusing @Put with @Get or @Post
- Ignoring the controller base path
- Misreading ':id' as a literal string
4. What is wrong with this NestJS route handler code?
@Controller('items')
export class ItemController {
@Delete('/remove')
removeItem() {
console.log('Item removed');
}
}medium
Solution
Step 1: Check the decorator and path usage
@Delete can have a path argument like '/remove', so this is valid.Step 2: Check the method implementation
The method only logs to console but does not return any response. HTTP handlers should return a response to the client.Final Answer:
The method should return a value, not just console.log -> Option DQuick Check:
Route handlers must return a response [OK]
Hint: Route handlers must return a response, not just log [OK]
Common Mistakes:
- Assuming console.log sends response
- Thinking decorator cannot have path
- Believing method name must match decorator
5. You want to create a NestJS controller with a route handler that updates a product by its ID using HTTP PUT. The handler should accept the ID as a route parameter and the updated data in the request body. Which code snippet correctly implements this?
hard
Solution
Step 1: Use the correct HTTP method and route parameter
Updating a resource uses HTTP PUT, so @Put(':id') is correct to capture the ID as a route parameter.Step 2: Use parameter decorators to access route and body data
@Param('id') extracts the ID from the route, and @Body() extracts the request body data. Both are required for this handler.Step 3: Check method signature and return
The method correctly returns a string confirming the update with the ID.Final Answer:
@Put(':id') updateProduct(@Param('id') id: string, @Body() data: any) { return `Updated product ${id}`; } -> Option BQuick Check:
Use @Put with ':id' and @Param plus @Body [OK]
Hint: Use @Put(':id') with @Param and @Body for updates [OK]
Common Mistakes:
- Missing route parameter in @Put decorator
- Not using @Param or @Body decorators
- Using wrong HTTP method like @Post for update
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
