Bird
Raised Fist0
NestJSframework~10 mins

Route handlers (GET, POST, PUT, DELETE) in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Route handlers (GET, POST, PUT, DELETE)
Client sends HTTP request
↓
NestJS Router receives request
↓
Match route path and HTTP method
↓
Call corresponding handler method
↓
Handler processes data and returns response
↓
Send HTTP response back to client
This flow shows how NestJS receives an HTTP request, matches it to a route handler by path and method, executes the handler, and sends back a response.
Execution Sample
NestJS
import { Controller, Get, Post, Put, Delete, Param } from '@nestjs/common';

@Controller('items')
export class ItemsController {
  @Get() getAll() { return 'Get all items'; }
  @Post() create() { return 'Create item'; }
  @Put(':id') update(@Param('id') id: string) { return `Update item ${id}`; }
  @Delete(':id') remove(@Param('id') id: string) { return `Delete item ${id}`; }
}
Defines route handlers for GET, POST, PUT, DELETE on 'items' path in a NestJS controller.
Execution Table
StepHTTP RequestRoute MatchedHandler CalledResponse Sent
1GET /itemsGET /itemsgetAll()'Get all items'
2POST /itemsPOST /itemscreate()'Create item'
3PUT /items/5PUT /items/:idupdate()'Update item'
4DELETE /items/5DELETE /items/:idremove()'Delete item'
5GET /unknownNo matchNone404 Not Found
💡 Execution stops when no matching route handler is found or response is sent.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
HTTP RequestNoneGET /itemsPOST /itemsPUT /items/5DELETE /items/5GET /unknown
Route MatchedNoneGET /itemsPOST /itemsPUT /items/:idDELETE /items/:idNone
Handler CalledNonegetAll()create()update()remove()None
Response SentNone'Get all items''Create item''Update item''Delete item''404 Not Found'
Key Moments - 3 Insights
Why does the PUT and DELETE handlers include ':id' in the route?
The ':id' is a route parameter that captures a value from the URL, allowing the handler to know which item to update or delete. This is shown in steps 3 and 4 where the route matched includes ':id'.
What happens if a request does not match any route handler?
As shown in step 5, if no route matches the request path and method, NestJS returns a 404 Not Found response and no handler is called.
Can multiple handlers respond to the same path with different HTTP methods?
Yes, as seen in steps 1 and 2, GET and POST handlers can share the same path '/items' but respond differently based on the HTTP method.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, which handler is called when the client sends a POST request to /items?
AgetAll()
Bupdate()
Ccreate()
Dremove()
💡 Hint
Check the row where HTTP Request is 'POST /items' in the execution table.
At which step does the route matching fail and no handler is called?
AStep 5
BStep 4
CStep 3
DStep 2
💡 Hint
Look for the step where 'Route Matched' is 'No match' and 'Handler Called' is 'None'.
If the PUT handler did not include ':id' in its route, what would happen when calling PUT /items/5?
AThe update() handler would still be called correctly.
BThe route would not match and a 404 would be returned.
CThe GET handler would be called instead.
DThe POST handler would be called instead.
💡 Hint
Check how route parameters like ':id' affect route matching in steps 3 and 4.
Concept Snapshot
NestJS route handlers respond to HTTP methods (GET, POST, PUT, DELETE).
Use decorators @Get(), @Post(), @Put(), @Delete() on controller methods.
Routes can include parameters like ':id' to capture URL parts.
NestJS matches request method and path to call the correct handler.
If no match, NestJS returns 404 automatically.
Full Transcript
In NestJS, route handlers are methods inside controllers decorated with HTTP method decorators like @Get, @Post, @Put, and @Delete. When a client sends an HTTP request, NestJS matches the request's path and method to the appropriate handler. For example, a GET request to '/items' calls the getAll() method decorated with @Get(). Routes can include parameters such as ':id' to capture dynamic parts of the URL, used in update() and remove() methods for PUT and DELETE requests. If no route matches, NestJS returns a 404 Not Found response. This flow ensures that each HTTP method and path combination triggers the correct code to handle the request and send back a response.

Practice

(1/5)
1. Which decorator is used in NestJS to create a route handler that responds to HTTP GET requests?
easy
A. @Get
B. @Post
C. @Put
D. @Delete

Solution

  1. 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.
  2. Step 2: Match the decorator to the GET method

    The decorator @Get is specifically designed to handle HTTP GET requests.
  3. Final Answer:

    @Get -> Option A
  4. Quick 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
A. @Post('/create') createItem() {}
B. Post('/create') createItem() {}
C. @post('/create') createItem() {}
D. @Put('/create') createItem() {}

Solution

  1. Step 1: Check the decorator syntax

    Decorators in NestJS start with '@' and are case-sensitive. The correct decorator for POST is '@Post'.
  2. 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.
  3. Final Answer:

    @Post('/create') createItem() {} -> Option A
  4. Quick 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
A. GET /users/:id
B. DELETE /users/:id
C. PUT /users/:id
D. POST /users/:id

Solution

  1. Step 1: Identify the controller base path

    The @Controller('users') decorator sets the base route path to '/users'.
  2. 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.
  3. Final Answer:

    PUT /users/:id -> Option C
  4. Quick 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
A. The method name must be 'deleteItem' for @Delete decorator
B. The decorator @Delete cannot have a path argument
C. The controller path 'items' is invalid
D. The method should return a value, not just console.log

Solution

  1. Step 1: Check the decorator and path usage

    @Delete can have a path argument like '/remove', so this is valid.
  2. 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.
  3. Final Answer:

    The method should return a value, not just console.log -> Option D
  4. Quick 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
A. @Put updateProduct(@Param('id') id: string, @Body() data: any) { return `Updated product ${id}`; }
B. @Put(':id') updateProduct(@Param('id') id: string, @Body() data: any) { return `Updated product ${id}`; }
C. @Put(':id') updateProduct(id: string, data: any) { return `Updated product ${id}`; }
D. @Post(':id') updateProduct(@Param('id') id: string, @Body() data: any) { return `Updated product ${id}`; }

Solution

  1. 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.
  2. 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.
  3. Step 3: Check method signature and return

    The method correctly returns a string confirming the update with the ID.
  4. Final Answer:

    @Put(':id') updateProduct(@Param('id') id: string, @Body() data: any) { return `Updated product ${id}`; } -> Option B
  5. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard