Controller Basics

@Controller and Route Decorators

A controller is a class with @Controller('prefix'). Each method gets a route decorator for an HTTP method. The value you return is sent as the response (objects and arrays become JSON).

src/products/products.controller.ts

import { Controller, Delete, Get, Patch, Post, Put } from '@nestjs/common';

@Controller('products')
export class ProductsController {
  @Get()          findAll()  { return 'GET /products'; }
  @Get(':id')     findOne()  { return 'GET /products/:id'; }
  @Post()         create()   { return 'POST /products'; }
  @Put(':id')     replace()  { return 'PUT /products/:id'; }
  @Patch(':id')   update()   { return 'PATCH /products/:id'; }
  @Delete(':id')  remove()   { return 'DELETE /products/:id'; }
}

Routes are Logged on Start

Example

Register the controller in ProductsModule and start the app. NestJS prints every mapped route:

npm run start:dev

Example output

[Nest] 21004  - LOG [RoutesResolver] ProductsController {/products}:
[Nest] 21004  - LOG [RouterExplorer] Mapped {/products, GET} route
[Nest] 21004  - LOG [RouterExplorer] Mapped {/products/:id, GET} route
[Nest] 21004  - LOG [RouterExplorer] Mapped {/products, POST} route
[Nest] 21004  - LOG [RouterExplorer] Mapped {/products/:id, PUT} route
[Nest] 21004  - LOG [RouterExplorer] Mapped {/products/:id, PATCH} route
[Nest] 21004  - LOG [RouterExplorer] Mapped {/products/:id, DELETE} route

Note: Order matters: put a fixed route like @Get('featured') before @Get(':id'), otherwise /products/featured is matched by :id with id = "featured".