Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Creating a Complete CRUD API Part One | Section
Building Backend Applications with Nest.js

bookCreating a Complete CRUD API Part One

Swipe to show menu

Now you will combine several Nest.js concepts and start building a small CRUD API.

CRUD stands for:

  • Create;
  • Read;
  • Update;
  • Delete.

In this part, you will set up a simple users API with routes for creating users and getting all users.

Start with the service:

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  private users = [
    { id: 1, name: 'Alice', age: 30 },
    { id: 2, name: 'Bob', age: 25 },
  ];

  getAllUsers() {
    return this.users;
  }

  createUser(user: { name: string; age: number }) {
    const newUser = {
      id: this.users.length + 1,
      ...user,
    };

    this.users.push(newUser);
    return newUser;
  }
}

Here is what is happening:

  • users: stores the current list of users;
  • getAllUsers(): returns all users;
  • createUser(): creates a new user and adds it to the array.

Now update the controller:

import { Controller, Get, Post, Body } from '@nestjs/common';
import { UsersService } from './users.service';

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

  @Get()
  getUsers() {
    return this.usersService.getAllUsers();
  }

  @Post()
  createUser(@Body() body: { name: string; age: number }) {
    return this.usersService.createUser(body);
  }
}

Here is what is happening:

  • @Get(): returns all users;
  • @Post(): creates a new user;
  • @Body(): gets data from the request body;
  • The controller passes the work to the service.

With this setup, your API can already:

  • Return all users;
  • Create a new user.

This is the first half of a CRUD API.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 21

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 21
some-alt