Build REST API with NestJS : A Step-by-Step Guide

A cutting-edge, contemporary Node.js framework called NestJS was created to create scalable, effective server-side applications. It is ideal for developers familiar with Angular or who like to construct organized and maintainable apps because it is based on TypeScript and uses strong typing and object-oriented programming principles. With the help of real-world examples, this blog article will walk you through the process of building REST API with NestJS.

What is NestJS?

A server-side application framework built on Node.js is called NestJS. It is constructed using TypeScript (but JavaScript is supported as well) and has a modular architecture that promotes better code structure and reuse.

Key Features of NestJS:
  • Extensible and Modular
  • Dependency Injection
  • Strong typing with TypeScript
  • Built-in support for testing
  • Middleware support
  • RESTful APIs, WebSockets, GraphQL

Why Use NestJS for Building REST APIs?

  • TypeScript Support: Because TypeScript is used in the construction of NestJS, type safety is provided, improving code maintainability and lowering the risk of runtime errors.
  • Modularity: NestJS encourages the use of modules, which makes your code highly organized and scalable.
  • Dependency Injection: NestJS’s built-in Dependency Injection (DI) helps in keeping the application loosely coupled, making it easier to test and maintain.
  • Performance: NestJS runs on top of Node.js, ensuring high performance and scalability.

Step-by-Step Guide to Building a REST API with NestJS

1. Install Node.js and Nest CLI

First, ensure that Node.js is installed. You can download it from here.

Next, install the NestJS Command Line Interface (CLI):

npm install -g @nestjs/cli

2. Create a New NestJS Project

Now, let’s create a new project with the NestJS CLI:

nest new nestjs-rest-api

Navigate to the project directory:

cd nestjs-rest-api

3. Create a New Module

Modules are a critical feature of NestJS and represent the building blocks of the application. Let’s create a users module for managing user-related operations:

nest generate module users

4. Create a Controller

Controllers are responsible for handling incoming HTTP requests and returning responses. Let’s create a UsersController:

nest generate controller users

In src/users/users.controller.ts, you’ll have something like this:

import { Controller, Get } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()
  getAllUsers() {
    return 'This will return a list of users';
  }
}

This controller now listens to the /users route and responds with a message when accessed.

5. Create a Service

Services handle the business logic of the application and are typically injected into controllers. Let’s create a UsersService to manage the users’ data:

nest generate service users

Now, in src/users/users.service.ts, define the logic to fetch user data:

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

@Injectable()
export class UsersService {
  private users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Doe' },
  ];

  findAll() {
    return this.users;
  }
}

6. Connect the Controller to the Service

Now, inject the UsersService into UsersController to fetch actual data:

In src/users/users.controller.ts:

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

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

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

When you access the /users route, it will now return the list of users.

7. Running the Application

To run the application, use the following command:

npm run start

Your application will run on http://localhost:3000. You can test the API by visiting, http://localhost:3000/users and you should see the list of users as JSON data.

8. Adding CRUD Operations

Let’s extend the API by adding more CRUD (Create, Read, Update, Delete) operations.

Add a User

In src/users/users.service.ts, add a method to create a new user:

create(user: { id: number; name: string }) {
  this.users.push(user);
  return user;
}

In the UsersController, add the following:

import { Controller, Get, Post, Body } from '@nestjs/common';

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

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

  @Post()
  createUser(@Body() user: { id: number; name: string }) {
    return this.usersService.create(user);
  }
}

Now you can send a POST request to http://localhost:3000/users with the following body to add a new user:

{
  "id": 3,
  "name": "Alice"
}

9. Connecting to a Database

Though we’ve used an in-memory array for simplicity, you can easily connect NestJS to databases like MySQL, PostgreSQL, or MongoDB using the appropriate ORM libraries (like TypeORM or Mongoose).

For example, to connect with a PostgreSQL database, install the TypeORM and PostgreSQL driver:

npm install --save @nestjs/typeorm typeorm pg

Then configure the database connection in app.module.ts:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'test',
      password: 'test',
      database: 'test',
      entities: [],
      synchronize: true,
    }),
  ],
})
export class AppModule {}

Conclusion

The foundational aspects of NestJS were covered in this tutorial, which included project setup, module, controller, and service creation, as well as the addition of CRUD functions. If developers want to use contemporary TypeScript capabilities to create server-side apps that are scalable and maintainable, NestJS is a great option.

By following this step-by-step guide, you can create efficient and well-structured REST APIs with NestJS. Stay tuned for more advanced topics like database integration, authentication, and more!

To learn more about NestJs please Click Here. Explore More features on Nodejs Click Here.

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.