How to create a controller with NestJs and handle various HTTP methods

Learn about creating controllers and handling HTTP methods in NestJS.

overview

NestJS controllers are responsible for receiving HTTP requests from clients and returning appropriate responses. This article details how to create controllers in NestJS to handle HTTP methods such as GET, POST, PUT, and DELETE.

nest.js v10.1.7
nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

Create a controller using NestJS CLI

NestJS makes it easy to create controllers using the CLI. Let’s create the users controller by running the CLI command below.

nest g co users

Running this command will automatically create the necessary files for the users controller.

src/
└── users/
    ├── users.controller.spec.ts
    └── users.controller.ts

Next, make sure you’ve added the controller you just created to the main module of your NestJS application, app.module.ts.

/src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersController } from './users/users.controller';

@Module({
  imports: [],
  controllers: [AppController, UsersController],
  providers: [AppService],
})
export class AppModule {}

Now you have created a routing controller for users.

Edit NestJS controller and handle HTTP methods

Next, edit the users controller you just created and configure it to handle the GET, POST, PUT, and DELETE HTTP methods.

/src/users/users.controller.ts


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

@Controller('users')
export class UsersController {
  @Get()
  getUsers(): string {
    return 'This is the response from the GET method';
  }

  @Post()
  createUser(): string {
    return 'This is the response from the POST method';
  }

  @Put()
  updateUser(): string {
    return 'This is the response from the PUT method';
  }

  @Delete()
  deleteUser(): string {
    return 'This is the response from the DELETE method';
  }
}

test

After the application starts, access http://localhost:3000/users and you will get the GET method response.

curl -X GET http://localhost:3000/users
curl -X POST http://localhost:3000/users
curl -X PUT http://localhost:3000/users
curl -X DELETE http://localhost:3000/users

Similarly, you can see responses for POST, PUT, and DELETE methods.

summary

In this article, we learned how to create controllers in NestJS to handle HTTP methods such as GET, POST, PUT, and DELETE. Let’s use this knowledge to develop applications using NestJS.