How to Build a REST API with NestJS (Step by Step)

By Abdelilah Ommane · Backend Developer

Short answer

Scaffold with the Nest CLI, then split logic into three pieces: a controller (handles HTTP), a service (holds business logic), and a module (wires them together). Use a DTO to validate incoming data.

1. Scaffold the project

npm i -g @nestjs/cli
nest new my-api
cd my-api
nest generate resource users

2. Controller (HTTP layer)

@Controller('users')
export class UsersController {
  constructor(private readonly users: UsersService) {}

  @Post()
  create(@Body() dto: CreateUserDto) {
    return this.users.create(dto);
  }

  @Get()
  findAll() {
    return this.users.findAll();
  }
}

3. Service (business logic)

@Injectable()
export class UsersService {
  private users: CreateUserDto[] = [];

  create(dto: CreateUserDto) {
    this.users.push(dto);
    return dto;
  }

  findAll() {
    return this.users;
  }
}

4. DTO (validation)

import { IsEmail, IsString } from 'class-validator';

export class CreateUserDto {
  @IsString() name: string;
  @IsEmail() email: string;
}

FAQ

NestJS vs Express for a REST API?

NestJS is built on top of Express (or Fastify) and adds a structured, opinionated architecture (modules, DI, decorators). Use it when you want maintainability at scale; use raw Express for tiny scripts.

How do I validate the DTO?

Enable ValidationPipe globally (app.useGlobalPipes(new ValidationPipe())) and decorate the DTO fields with class-validator rules as shown above.

← All guides