Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 42 ยท Projects

Project: Todo REST API

Build a Todo REST API in NestJS: module layout, DTOs with validation, an in-memory service, filtering, pagination, an error filter and tests.

In this project you build a small but complete REST API for todo items: create, list (with filtering and pagination), read, update and delete. It uses nearly everything from the first chapters of this tutorial: a feature module, a controller, a provider holding the data, DTOs with validation, consistent errors from exception filters and tests as in Testing Nest Applications.

The real Nest files are shown as read-only code, since they need Node and npm. Next to them you get a runnable stand-in written in plain Node that implements the same layers (route table, id parsing, validation with whitelisting, service, error mapping) so you can send requests and watch every status code. The stand-in is not Nest; it is a model of what Nest's request flow does for you.

The API

POST /todos Create a todo. Returns 201.
GET /todos List with filter and paging.
GET /todos/:id One todo, or 404.
PATCH, DELETE Update fields, remove (204).
1 / 2

Step 1: layout

Generate the project and the feature with the CLI (Project Structure and the CLI):

Terminal
nest new todo-api
cd todo-api
nest generate module todos
nest generate controller todos --no-spec
nest generate service todos --no-spec

You end up with a feature folder that owns everything about todos:

Text
src/
  main.ts
  app.module.ts
  common/
    all-exceptions.filter.ts
  todos/
    dto/
      create-todo.dto.ts
      update-todo.dto.ts
      list-todos.query.ts
    todo.interface.ts
    todos.controller.ts
    todos.service.ts
    todos.module.ts
test/
  todos.e2e-spec.ts

TodosModule declares the controller and the service and is imported by AppModule. Nothing else needs the service, so it is not exported.

Step 2: DTOs and validation

A DTO is a class, so decorators can describe the rules and the validation pipe can read them. Install class-validator, class-transformer and @nestjs/mapped-types first.

TypeScript
// dto/create-todo.dto.ts
import { IsBoolean, IsNotEmpty, IsOptional, IsString, MaxLength } from 'class-validator';

export class CreateTodoDto {
  @IsString()
  @IsNotEmpty()
  @MaxLength(100)
  title: string;

  @IsOptional()
  @IsBoolean()
  done?: boolean;
}
TypeScript
// dto/update-todo.dto.ts
import { PartialType } from '@nestjs/mapped-types';
import { CreateTodoDto } from './create-todo.dto';

export class UpdateTodoDto extends PartialType(CreateTodoDto) {}

PartialType copies the class with every property optional and keeps the decorators, so a PATCH body may contain any subset of the create fields. Query strings arrive as text, so the list query needs a transformation:

TypeScript
// dto/list-todos.query.ts
import { Transform, Type } from 'class-transformer';
import { IsBoolean, IsInt, IsOptional, IsString, Max, Min } from 'class-validator';

export class ListTodosQuery {
  @IsOptional()
  @Transform(({ value }) => value === 'true' ? true : value === 'false' ? false : value)
  @IsBoolean()
  done?: boolean;

  @IsOptional() @IsString() q?: string;

  @IsOptional() @Type(() => Number) @IsInt() @Min(1) page: number = 1;
  @IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(50) limit: number = 10;
}

Turn on the pipe for the whole app in main.ts:

TypeScript
app.useGlobalPipes(new ValidationPipe({
  whitelist: true,
  forbidNonWhitelisted: true,
  transform: true,
}));

With these options an unknown property (such as priority) is rejected, strings become numbers where declared, and defaults like page = 1 apply because transform: true creates real DTO instances.

Step 3: the service

The service holds the rules and, for now, the data in memory. A database later changes only this file, a theme taken up in Connecting to a Database.

TypeScript
// todos.service.ts
@Injectable()
export class TodosService {
  private readonly todos = new Map<number, Todo>();
  private nextId = 1;

  create(dto: CreateTodoDto): Todo {
    const todo: Todo = { id: this.nextId++, title: dto.title, done: dto.done ?? false };
    this.todos.set(todo.id, todo);
    return todo;
  }

  findAll(query: ListTodosQuery) {
    let items = [...this.todos.values()];
    if (query.done !== undefined) items = items.filter((t) => t.done === query.done);
    if (query.q) items = items.filter((t) => t.title.toLowerCase().includes(query.q!.toLowerCase()));
    const total = items.length;
    const start = (query.page - 1) * query.limit;
    return { data: items.slice(start, start + query.limit), meta: { page: query.page, limit: query.limit, total } };
  }

  findOne(id: number): Todo {
    const todo = this.todos.get(id);
    if (!todo) throw new NotFoundException(`Todo ${id} not found`);
    return todo;
  }

  update(id: number, dto: UpdateTodoDto): Todo {
    return Object.assign(this.findOne(id), dto);
  }

  remove(id: number): void {
    this.findOne(id);
    this.todos.delete(id);
  }
}

Note that update is safe against mass assignment only because the pipe whitelisted the DTO first (Security and Hardening). The service throws Nest's own NotFoundException, so it does not know anything about HTTP status numbers.

Step 4: the controller

TypeScript
// todos.controller.ts
@Controller('todos')
export class TodosController {
  constructor(private readonly todos: TodosService) {}

  @Post()
  create(@Body() dto: CreateTodoDto) {
    return this.todos.create(dto);          // POST returns 201 by default
  }

  @Get()
  findAll(@Query() query: ListTodosQuery) {
    return this.todos.findAll(query);
  }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.todos.findOne(id);
  }

  @Patch(':id')
  update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateTodoDto) {
    return this.todos.update(id, dto);
  }

  @Delete(':id')
  @HttpCode(204)
  remove(@Param('id', ParseIntPipe) id: number) {
    this.todos.remove(id);
  }
}

The controller is thin on purpose: it extracts request data (Reading Request Data), calls the service and returns a value. ParseIntPipe turns /todos/abc into a 400 before the handler runs.

Step 5: one error shape

Nest already turns every HttpException into JSON with statusCode, message and error. A global filter lets you add fields such as the path and make unexpected errors safe:

TypeScript
// common/all-exceptions.filter.ts
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const status = exception instanceof HttpException ? exception.getStatus() : 500;
    const body = exception instanceof HttpException
      ? exception.getResponse()
      : { message: 'Internal server error' };

    response.status(status).json({
      ...(typeof body === 'string' ? { message: body } : body),
      statusCode: status,
      path: request.url,
    });
  }
}

Register it with { provide: APP_FILTER, useClass: AllExceptionsFilter } in AppModule. An unexpected error then returns a short 500 and never leaks a stack trace.

The stand-in: the whole flow in plain Node

The first runnable example is the domain core: the validator with whitelisting and the service with filtering and pagination, as plain functions. It is the logic that the DTO classes and the service class express in Nest.

Node.js Validation, whitelisting, filtering and paging

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each rejected body produces a list of messages, as the real ValidationPipe does (it answers with an array of strings under message). The page-2 query skips the first two items, and total counts everything that matched before slicing, which clients need to build page links.

The second example is the whole API: a route table, id parsing like ParseIntPipe, the validation from above, the service and an error filter, driven by a small client session. It writes the app to a module file so a test file can import it too. Then it runs five tests with the real node:test runner, using the same run() trick as in Testing Nest Applications.

Node.js The Todo API end to end, with tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The session shows every layer working: the validation failure lists both problems at once, the bad id is stopped before the service is called, the missing id yields the same error shape, and DELETE returns 204 with no body. In Nest the same results come from the pipe, ParseIntPipe, NotFoundException and @HttpCode(204).

Step 6: tests

Unit-test the service by creating it directly or through Test.createTestingModule, then add an e2e test with supertest for the HTTP behavior, repeating the global pipe from main.ts (Testing Nest Applications):

TypeScript
it('POST /todos rejects unknown properties', () =>
  request(app.getHttpServer())
    .post('/todos')
    .send({ title: 'A', role: 'admin' })
    .expect(400));

it('GET /todos/abc is a 400', () =>
  request(app.getHttpServer()).get('/todos/abc').expect(400));

it('DELETE removes the todo', async () => {
  const { body } = await request(app.getHttpServer()).post('/todos').send({ title: 'A' });
  await request(app.getHttpServer()).delete('/todos/' + body.id).expect(204);
  await request(app.getHttpServer()).get('/todos/' + body.id).expect(404);
});

Ideas to extend it

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is UpdateTodoDto built with PartialType(CreateTodoDto)?

    PartialType copies the class, marks all properties optional and keeps the decorators, so a PATCH body can contain any valid subset of fields.
  2. 2. A request to GET /todos/abc returns 400 before the handler runs. Which part is responsible?

    A pipe attached to the route parameter transforms or rejects the value before the handler is called.
  3. 3. Why does the service throw NotFoundException rather than returning null?

    Throwing an HttpException lets Nest (and your filters) produce the response. The controller needs no if-statements for the missing case.
  4. 4. With whitelist and forbidNonWhitelisted on, what happens to {"title":"A","role":"admin"} posted to /todos?

    forbidNonWhitelisted turns the stripping behavior into a 400 error that lists the undeclared property.

Summary

  • A feature module owns its controller, service and DTOs; the controller stays thin and the service holds rules and data.
  • DTO classes with class-validator decorators plus a global ValidationPipe({ whitelist, forbidNonWhitelisted, transform }) validate and clean input; PartialType derives the update DTO.
  • ParseIntPipe, NotFoundException and @HttpCode(204) give correct status codes without manual checks.
  • A global exception filter keeps every error in one shape and hides internals.
  • Test the service directly and the HTTP layer with e2e tests that repeat the global pipe.

Next, add identity in Project: Auth Service.