Open In App

How to Build a Simple and Scalable Web API using Nest.js and Typescript ?

Improve
Improve
Like Article
Like
Save
Share
Report

Before getting started with Nest.js, we will recommend reading this Article first: ExpressJS vs NestJS.

Why learn Nest.js?

We have a lot of server-side JavaScript frameworks so what does Nest special in it? See, there are tons of JavaScript libraries, helpers, and tools that exist for Node.js, but none of them effectively solves the problem of Maintenance of the code base. Yes, maintaining the codebase is as important as maintaining the performance of the server. Nest.js provides the best architecture when it comes to scaling. Nest.js is best for microservices. Nest.js fully supports TypeScript and it has the best ever error handling in the market. Maintaining the Nest.js Application is a breeze!

“Nest provides an out-of-the-box application architecture which allows developers and teams to create highly testable, scalable, loosely coupled, and easily maintainable applications. The architecture is heavily inspired by Angular.” 

Let’s get started! We will try to keep this article short and easy. You can find my GitHub repository at the end of this Article. We will be creating a to-do web API to understand Nest.js.

Installation:

Step 1: Installing Nest.JS is pretty simple. We will be using package managers to install Nest.

$ npm i -g @nestjs/cli

Step 2: After installing Nest globally, we can create our project with the next command.

$ nest new task-api

Step 3: To start the application type the nest commands.

$ cd task-api
$ npm install
$ npm run start

Step 4: Find core files in the src/ directory. On successful Installation, you will find:

  • main.ts
  • app.controller.ts
  • app.service.ts
  • app.module.ts

Note:

  • Modules are the basic building blocks in Nest.js
  • Every module in Nest.js contains three files: ‘controller.ts’, ‘service.ts’, ‘module.ts’
  • The app module is the root module of your server-side nest web application, and it contains other modules.

Project Structure: The project should look like this:

The folder structure of Nest.JS Application

Steps to Build web API using Nest.js and Typescript: Follow the below steps one by one to build a web API:

Step 1: Let’s create Task Module in our application using the Nest CLI command:

$ nest generate module Task

Inside the task folder you will find a similar root module folder structure. Inside the ‘task.module.ts’ file you will find:

Javascript




import { Module } from '@nestjs/common';
import { TaskController } from './task.controller';
import { TaskService } from './task.service';
  
@Module({
    controllers: [TaskController],
    providers: [TaskService],
    imports: [
    ],
})
export class TaskModule { }


Nest.js automatically creates the required controller and service files for initial development.

Step 2: Create ‘dtos’ folder in ‘/src/Task‘. and add the ‘task.dto.ts’ file.

Note: DTOs stand for data transfer objects. A DTO is necessary to validate the data in each request for this reason we use the class-validator library.

$ npm install class-validator

See the code below:

Javascript




import { IsInt, IsString, IsDate, IsNotEmpty, IsOptional } from 'class-validator';
  
export class Task {
    @IsInt()
    @IsOptional()
    id: number;
  
    @IsString()
    @IsNotEmpty()
    readonly title: string;
  
    @IsString()
    @IsOptional()
    description;
  
    @IsOptional()
    @IsDate()
    @IsNotEmpty()
    createdOn;
}


Step 3: Add methods in the ‘task.service.ts’ file. We will be storing tasks in an array, locally on the server to maintain the simplicity of the Article

Services contain methods that implement business logic. Simple JavaScript functions are responsible to handle the transfer and manipulation of data.

Javascript




import { Task } from 'src/dtos/task.dto';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
  
@Injectable()
export class TaskService {
  
    // We will be storing our task in this array, 
    // to maintain simplicity of this article 
  
    private tasks: Task[] = [];
  
    // We will be using these methods in 
    // our Task controller. 
  
    addTask(task: Task): Task {
        const taskToAdd: Task = {
            title: task.title,
            id: this.tasks.length + 1,
            description: task.description,
            createdOn: new Date(),
        };
        this.tasks.push(taskToAdd);
        return taskToAdd;
    }
  
    listTaskById(id: number): Task {
        const result = this.tasks.find((item) => item.id === id);
        if (result) {
            return result;
        } else {
            throw new HttpException(
                'Task not found', HttpStatus.FORBIDDEN);
        }
    }
}


Step 4: Add methods in the ‘task.controller.ts’ file.

A controller is a simple class with the decorator @Controller(‘task’), which indicates this will be listening the requests made at ‘/src/Task’ endpoint. To handle the different HTTP requests methods NestJS provides us methods: @Get, @Post, @Put(), @Delete(), @Patch().

Javascript




import {
    Body,
    Controller,
    Get,
    Post,
    Param,
    ParseIntPipe,
    Request,
} from '@nestjs/common';
import { Task } from './interfaces/task.dto';
import { TaskService } from './task.service';
  
@Controller('task')
export class TaskController {
    constructor(private taskService: TaskService) { }
  
    // It will handle all HTTP POST Requests made 
    // to '/task' endpoint from client.
    @Post()
    async addTask(@Body() task: Task) {
        const addedTask = this.taskService.addTask(task);
        return addedTask;
    }
  
    // It will handle all HTTP GET Requests made 
    // to '/task' endpoint from client.
    @Get(':id')
    async listTaskById(@Param('id', ParseIntPipe) id: number) {
        if (id) {
            return this.taskService.listTaskById(id);
        }
        return 'Id not found!';
    }
}


Step 5: Setup ‘task.module.ts’ file in ‘/src/Task’ folder, and add providers and controllers.

Javascript




import { Module } from '@nestjs/common';
import { TaskController } from './task.controller';
import { TaskService } from './task.service';
  
  
@Module({
    controllers: [TaskController],
    providers: [TaskService],
    imports: [
        // Nothing to import in task module
    ],
})
export class TaskModule { }


Step 6: Setup the ‘app.module.ts’ file in the ‘/src‘ folder, and import the Task module.

Javascript




import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TaskModule } from './task/task.module';
  
@Module({
    imports: [TaskModule],
    controllers: [AppController],
    providers: [AppService],
})
export class AppModule { }


Step 7: Make sure you have a similar code in ‘/src/main.ts’. This code will initialize our web API.

Javascript




import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { useContainer } from 'class-validator';
import { AppModule } from './app.module';
  
async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.useGlobalPipes(new ValidationPipe(
        { whitelist: true, transform: true }));
    await app.listen(3000);
}
bootstrap();


Steps to run the application: Now we are ready to run our NestJS web API on localhost/3000: 

$ nest start

 

Output: We will be using Postman to test out Nest.JS Task Web API. You can test it using Postman or open the URL in Browser. 

1. Make a POST request on endpoint ‘http://localhost:3000/task’ in Postman as shown below:

 

2. Make a GET request on endpoint ‘http://localhost:3000/task/1’ in Postman as shown below:

 

Hope you enjoyed this article, you can check the code in the GitHub repository.



Last Updated : 14 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads