Controllers: Handling Requests
Controllers: Handling Requests
Controllers are the entry point for incoming requests. Their job is narrow and important: receive a request, delegate the work to a service, and return a response. Keeping controllers thin — routing only, no business logic — is one of the most important habits in NestJS.
Defining a controller
A controller is a class decorated with @Controller(). The string you pass becomes the route prefix for every method inside:
Here @Controller('users') + @Get() maps to GET /users.
HTTP method decorators
Each HTTP verb has a decorator: @Get(), @Post(), @Put(), @Patch(), @Delete(). Pass a path segment to extend the route:
Reading route parameters
Dynamic segments use :name in the path and the @Param() decorator to read them:
42 arrives as the string '42'. Converting and validating it is the job of pipes, covered later in this course.
Query parameters and the request body
Use @Query() for the query string and @Body() for the request payload:
@Req(), but using @Param(), @Query(), and @Body() keeps your handlers framework-agnostic, typed, and far easier to test.
Status codes and responses
By default NestJS returns 200 (and 201 for @Post()). Override with @HttpCode(), and whatever you return is automatically serialised to JSON:
Summary
Controllers map requests to handler methods using @Controller() and the HTTP-verb decorators, and read input with @Param(), @Query(), and @Body(). Returned values are serialised to JSON automatically. The golden rule: controllers route, services do the work. Next we will build those services.