How to create RESTful API in Nest JS? Step by step guidelines!

nadim_ch0wdhury

Nadim Chowdhury

Posted on June 4, 2024

How to create RESTful API in Nest JS? Step by step guidelines!

Creating a RESTful API in NestJS involves several steps. Here’s a step-by-step theoretical guide:

Step 1: Setup a New NestJS Project

  1. Install Nest CLI:
   npm install -g @nestjs/cli
Enter fullscreen mode Exit fullscreen mode
  1. Create a New Project:
   nest new project-name
Enter fullscreen mode Exit fullscreen mode
  1. Navigate to the Project Directory:
   cd project-name
Enter fullscreen mode Exit fullscreen mode

Step 2: Generate a Module, Controller, and Service

  1. Generate a Module:
   nest g module user
Enter fullscreen mode Exit fullscreen mode
  1. Generate a Controller:
   nest g controller user
Enter fullscreen mode Exit fullscreen mode
  1. Generate a Service:
   nest g service user
Enter fullscreen mode Exit fullscreen mode

Step 3: Define the User Entity

  1. Create a User Entity: Create the src/user/user.entity.ts file:
   export class User {
     id: number;
     name: string;
     email: string;
   }
Enter fullscreen mode Exit fullscreen mode

Step 4: Implement the User Service

  1. Implement Service Logic: Open src/user/user.service.ts and implement the service methods:
   import { Injectable } from '@nestjs/common';
   import { User } from './user.entity';

   @Injectable()
   export class UserService {
     private users: User[] = [];
     private idCounter = 1;

     findAll(): User[] {
       return this.users;
     }

     findOne(id: number): User {
       return this.users.find(user => user.id === id);
     }

     create(user: User): User {
       user.id = this.idCounter++;
       this.users.push(user);
       return user;
     }

     update(id: number, updatedUser: Partial<User>): User {
       const user = this.findOne(id);
       if (user) {
         Object.assign(user, updatedUser);
       }
       return user;
     }

     delete(id: number): void {
       this.users = this.users.filter(user => user.id !== id);
     }
   }
Enter fullscreen mode Exit fullscreen mode

Step 5: Implement the User Controller

  1. Implement Controller Logic: Open src/user/user.controller.ts and define the routes:
   import { Controller, Get, Post, Put, Delete, Param, Body } from '@nestjs/common';
   import { UserService } from './user.service';
   import { User } from './user.entity';

   @Controller('users')
   export class UserController {
     constructor(private readonly userService: UserService) {}

     @Get()
     findAll(): User[] {
       return this.userService.findAll();
     }

     @Get(':id')
     findOne(@Param('id') id: string): User {
       return this.userService.findOne(+id);
     }

     @Post()
     create(@Body() user: User): User {
       return this.userService.create(user);
     }

     @Put(':id')
     update(@Param('id') id: string, @Body() updatedUser: Partial<User>): User {
       return this.userService.update(+id, updatedUser);
     }

     @Delete(':id')
     delete(@Param('id') id: string): void {
       this.userService.delete(+id);
     }
   }
Enter fullscreen mode Exit fullscreen mode

Step 6: Update the User Module

  1. Update the User Module: Open src/user/user.module.ts and update it to include the controller and service:
   import { Module } from '@nestjs/common';
   import { UserController } from './user.controller';
   import { UserService } from './user.service';

   @Module({
     controllers: [UserController],
     providers: [UserService],
   })
   export class UserModule {}
Enter fullscreen mode Exit fullscreen mode

Step 7: Integrate the User Module into the App Module

  1. Update the App Module: Open src/app.module.ts and update it to include the User module:
   import { Module } from '@nestjs/common';
   import { UserModule } from './user/user.module';

   @Module({
     imports: [UserModule],
   })
   export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Step 8: Run the Application

  1. Start the NestJS Application:
   npm run start:dev
Enter fullscreen mode Exit fullscreen mode

Step 9: Test the RESTful API

  1. Test the API Endpoints: Use a tool like Postman or curl to test the RESTful API endpoints:
    • GET /users: Retrieve all users.
    • GET /users/:id: Retrieve a user by ID.
    • POST /users: Create a new user.
    • PUT /users/:id: Update a user by ID.
    • DELETE /users/:id: Delete a user by ID.

This guide provides a foundational approach to creating a RESTful API in NestJS. You can further expand and customize it based on your application's requirements.

If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!

Disclaimer: This content is generated by AI.

💖 💪 🙅 🚩
nadim_ch0wdhury
Nadim Chowdhury

Posted on June 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related