0
0
NestJSframework~5 mins

Route handlers (GET, POST, PUT, DELETE) in NestJS

Choose your learning style9 modes available
Introduction

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.

When you want to show a list of items on a webpage (GET).
When a user submits a form to add new data (POST).
When you need to update existing information (PUT).
When you want to remove something from your app (DELETE).
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
This handles GET requests to '/users' and returns a simple message.
NestJS
@Get('users')
getUsers() {
  return 'List of users';
}
This handles POST requests to '/users' to add a new user.
NestJS
@Post('users')
createUser() {
  return 'User created';
}
This handles PUT requests to update a user by ID.
NestJS
@Put('users/:id')
updateUser() {
  return 'User updated';
}
This handles DELETE requests to remove a user by ID.
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' };
  }
}
OutputSuccess
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.