Open In App

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

Last Updated : 14 Sep, 2022
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.



Similar Reads

How to add Scalable Vector Graphics to your web page ?
In this article, we will learn how can we add Scalable Vector Graphics (SVG) to our web page & will also understand its implementation through the example. SVG is a type of image format which is written in XML for vector-based graphics. Every element and every attribute in SVG files can be animated. Scalable Vector Graphics images do not lose t
3 min read
D3.js nest.sortKeys() Function
D3.js is a library built with JavaScript and particularly used for data visualization. The nest.sortKeys() function is used to sort the keys in a particular order i.e. ascending or descending. Syntax: nest.sortkeys( comparatorFunction ) Parameters: This function accepts a single parameter comparatorFunction that is used to specify how to sort the k
2 min read
D3.js nest() Function
D3.js is a library built with javascript and particularly used for data visualization. D3.nest() function is used to group the data as groupBy clause does in SQL. It groups the data on the basis of keys and values. Syntax: d3.nest() Parameters: This function does not accept any parameters. Return Value: It returns the object with several properties
2 min read
D3.js nest.map() Function
nest.map() function in D3.js is used to form a nested map. The map contains a key-value pair determined by the key function which was executed very first. If no keys are declared or defined than map function returns the original array as it is. Syntax: nest.map(array) Parameters: It takes the collection array as the input. Return: Below are a few e
2 min read
D3.js nest.key() Function
nest.key() function in D3.js is used to register a new key function which is invoked for each element in the input array. Whenever a new key is registered, it is then pushed in the array to the end. Syntax: nest.keys(key) Parameters: It takes only one parameter i.e the key function. Return: It returns a string identifier. Below given are few exampl
2 min read
D3.js nest.entries() function
The nest.entries() function in D3.js is used to generate the nest and is applies a nest operator to every level of hierarchy rather than the outmost layer only. Syntax: nest.entries(array) Parameters: It takes only one parameter given above and described below. Array: It is the array of objects. Return Value: It returns the array of key-value entri
2 min read
D3.js nest.object() Function
The nest.object() function in D3.js is used to apply the nest operator to the given array and returns the nested object of key-value pair. Syntax: nest.object( array ) Parameters: This function accepts single parameter as mentioned above and described below: Array: This parameter holds the array of objects. Return Value: It returns the object. Belo
2 min read
How to Create Nested Arrays from a Nest of Arrays in JavaScript ?
Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional structures. Such nested arrays can represent various dat
3 min read
Build a Simple static file web server in Node.js
In this article, we will build a static file web server which will list out all the files in the directory and on clicking the file name it displays the file content. Steps for creating a static file server is as follows: Step 1: Importing necessary modules, and defining MIME types which helps browser to understand the type of file that is being se
4 min read
How to Build a Simple Web Server with Node.js ?
Introduction: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and it’s not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make a web server using node.js. Creating
2 min read