Run the following command in your terminal:
npm install -g @nestjs/cli
Create a new NestJS application:
nest new my-api
Navigate to the project directory:
cd my-api
nest generate resource users
This will create the necessary files in src/users/
.
Edit src/users/users.controller.ts
:
import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
// The @Controller decorator marks this class as a controller
// 'users' defines the route prefix for this controller
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
// The @Post decorator marks this as a POST endpoint
// @Body() extracts the request body and maps it to CreateUserDto
@Post()
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
// The @Get decorator marks this as a GET endpoint
// This retrieves all users
@Get()
findAll() {
return this.usersService.findAll();
}
// The @Get(':id') decorator defines a dynamic route parameter
// @Param('id') extracts the id parameter from the URL
@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findOne(id);
}
}
Modify src/users/users.service.ts
:
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
// The @Injectable decorator marks this class as a service
// This allows it to be injected as a dependency
@Injectable()
export class UsersService {
private users = [];
// Method to create a new user
create(createUserDto: CreateUserDto) {
const newUser = { id: Date.now().toString(), ...createUserDto };
this.users.push(newUser);
return newUser;
}
// Method to retrieve all users
findAll() {
return this.users;
}
// Method to retrieve a single user by ID
findOne(id: string) {
return this.users.find(user => user.id === id);
}
}
Create src/users/dto/create-user.dto.ts
:
// DTO ensures data validation and type safety
export class CreateUserDto {
name: string;
email: string;
}
Run the server in development mode:
npm run start:dev
You can test the API using Postman, cURL, or any REST client:
POST /users
Content-Type: application/json
{
"name": "Alice",
"email": "[email protected]"
}
GET /users
GET /users/:id
🎉 Congratulations! You've successfully built a simple API using NestJS and TypeScript!