How to create RESTful API in Nest JS? Step by step guidelines!
Nadim Chowdhury
Posted on June 4, 2024
Creating a RESTful API in NestJS involves several steps. Here’s a step-by-step theoretical guide:
Step 1: Setup a New NestJS Project
- Install Nest CLI:
npm install -g @nestjs/cli
- Create a New Project:
nest new project-name
- Navigate to the Project Directory:
cd project-name
Step 2: Generate a Module, Controller, and Service
- Generate a Module:
nest g module user
- Generate a Controller:
nest g controller user
- Generate a Service:
nest g service user
Step 3: Define the User Entity
-
Create a User Entity:
Create the
src/user/user.entity.ts
file:
export class User {
id: number;
name: string;
email: string;
}
Step 4: Implement the User Service
-
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);
}
}
Step 5: Implement the User Controller
-
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);
}
}
Step 6: Update the User Module
-
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 {}
Step 7: Integrate the User Module into the App Module
-
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 {}
Step 8: Run the Application
- Start the NestJS Application:
npm run start:dev
Step 9: Test the RESTful API
-
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 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
privacy Caught in the Crunch My Journey from Snacks to 2 Million Exposed Users Privacy
November 30, 2024
devchallenge Submission for the DevCycle Feature Flag Challenge: Feature Flag Funhouse
November 30, 2024