How to Build a Simple and Scalable Web API using Nest.js and Typescript ?
Last Updated :
25 Jul, 2024
NestJS is a progressive Node.js framework that leverages TypeScript and is built on top of Express.js. It’s designed to provide an application architecture out of the box, which helps to create highly testable, maintainable, and scalable applications. In this guide, we will walk through the steps to build a simple and scalable Web API using NestJS and TypeScript.
"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 Steps
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:
Steps to Build web API using Nest.js and Typescript
Step 1: Let's create Task Module in our application using the Nest CLI command
$ nest generate module Task
Example: Inside the task folder you will find a similar root module folder structure. Inside the 'task.module.ts' file you will find:
JavaScript
// app.js
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
Example: Implementation to use class validator library
JavaScript
// app.js
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
// app.js
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
// task.controller.ts
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
// task.module.ts
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
// app.module.ts
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
// main.ts
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 build and publish an NPM package for React using Typescript?
In development, creating and distributing reusable components is essential for building scalable and maintainable applications. With the popularity of TypeScript and React, you can easily package and share your components as NPM packages. This tutorial will teach us how to create and release our NPM
4 min read
How to use TypeScript to build Node.js API with Express ?
TypeScript is a powerful version of JavaScript that incorporates static typing and other features, making it easy to build and maintain large applications. Combined with Node.js and Express, TypeScript can enhance your development experience by providing better type safety and tools. This guide will
4 min read
How to use Async/Await with a Promise in TypeScript ?
In TypeScript, you can use async and await with a Promise to simplify asynchronous code and make it more readable.What is a Promise?A promise in TypeScript is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that may be avai
3 min read
How to Build a REST API with Next.js 13?
Next.js is the most widely used React framework. Next.js 13.2 introduced a new file-based routing mechanism, called App Router, for building React frontend and serverless backend. In this article, we will be building a simple REST API using Next.js Route HandlersTable of ContentNext.js Route Handler
7 min read
How to compile multiple Typescript files into a single file ?
In this article, we will learn how to compile multiple Typescript files into a single file. There are two approaches that can be followed here: Approach 1: Compiling multiple Typescript files into a single JavaScript file. We simply use the following syntax: Syntax: tsc --out outputFile.js typeScrip
4 min read
Build an Application Like Google Docs Using React and MongoDB
In this article, we will create applications like Google Docs Made In React and MongoDB. This project basically implements functional components and manages the state accordingly. The user uses particular tools and format their document like Google Docs and save their work as well. The logic of Goog
6 min read
How to Build a RESTful API Using Node, Express, and MongoDB ?
This article guides developers through the process of creating a RESTful API using Node.js, Express.js, and MongoDB. It covers setting up the environment, defining routes, implementing CRUD operations, and integrating with MongoDB for data storage, providing a comprehensive introduction to building
6 min read
Build a Social Media REST API Using Node.js: A Complete Guide
Developers build an API(Application Programming Interface) that allows other systems to interact with their Applicationâs functionalities and data. In simple words, API is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data and
15+ min read
How to Create Objects with Dynamic Keys in TypeScript ?
In TypeScript, objects with dynamic keys are those where the key names are not fixed and can be dynamically determined at runtime. This allows the creation of flexible data structures where properties can be added or accessed using variables, providing more versatile type definitions.These are the f
3 min read
Build an Online Code Compiler using React.js and Node.js
In this article, we will learn how to build an online code compiler using React.js as frontend and Express.js as backend. Users will be able to write C, C++, Python, and Java code with proper syntax highlighting as well as compile and execute it online. The main objective of building an online compi
7 min read