Unlocking Backend Brilliance: A Journey into NestJS for Creating RESTful API
Praveen Kumar
Software Engineer II @ JPMorgan Chase | Mentor for Python, Java, Node.js, Microservices | Interview Coach | Guiding Professionals on the Latest Tech Trends
If you're just starting out on your journey in backend development, you're in for a treat. NestJS is not your average Node.js framework – it's a powerhouse that seamlessly integrates TypeScript, offering a structured approach to crafting robust server-side applications.
In this article, we're embarking on a concise yet hands-on exploration of NestJS. By the time you reach the end, you'll be equipped with the knowledge and confidence to create your very own RESTful APIs. ??
So, buckle up and get ready to unlock the full potential of NestJS! Let's dive in together and pave the way for your future endeavors in backend development. ??
Prerequisites
Before diving into NestJS, make sure you have Node.js and npm (Node Package Manager) installed on your machine. If you haven't already installed them, you can download them from the official Node.js website here. Once you have Node.js and npm set up, you're all set to get started! ??
Project Setup
$ npx @nestjs/cli new book-management-api
After running above command you will be asked to select a package manager of the project, for this project we will be selecting npm
The above command will initiate the creation of a new NestJS project named "book-management-api" in the directory you're currently in.
Navigate into the Project Directory:
Once the command completes successfully, let's navigate into our newly generated project directory. Use the following command:
$ cd book-management-api
Now, you're inside your NestJS project directory, ready to start building amazing things!
With above simple steps, you've laid the foundation for your NestJS project. Now that we have our NestJS project set up, let's take a tour of the default directory structure. Understanding the layout of the project will help us navigate and organize our code effectively. Below is the folder structure of any nest.js project by default
Let's take bit of our time understanding each of the files and folders of our project
Now that we have our Nest.js project set up and we're familiar with its directory structure, let's dive into how we can use it to create a RESTful API.
But wait... Do you know what exactly REST API is ?
If not do not worry I will explain it for you in brief read the below section
REST API (Representational State Transfer)
REST, or Representational State Transfer, is an architectural style for designing networked applications. It relies on a stateless, client-server communication protocol, typically HTTP, and follows a set of principles for defining how resources are identified and addressed. In a RESTful architecture, resources are represented as URIs (Uniform Resource Identifiers), and interactions with these resources are performed using standard HTTP methods like GET, POST, PUT, DELETE, etc.
If you want to know in more details then I would suggest you going through this blog.
As now all of you are familiar with REST API architecture let's create an API using Nest.js
Creating a REST API with Nest.js:
Now that we have our Nest.js project set up and we're familiar with its directory structure, let's dive into how we can use it to create a RESTful API. Let's build a simple book management API by following below simple steps:
Define Your Data Model:
Before creating endpoints, it's important to define the structure of your data. This could be done using TypeScript interfaces or classes. For example, as we're building a simple book management API, we will have a Book interface with properties like id, title, author, and description.So let's define a simple data model for books. Create a file named book.model.ts in the src directory with the following content:
// src/book.model.ts
export interface Book {
id: number;
title: string;
author: string;
description: string;
}
Implement Services:
Services in Nest.js contain the business logic of your application. They are responsible for interacting with data sources (like databases) and performing any necessary operations.
For our Book Management API, let's create BookService by using Nest CLI
nest generate service books
This will create a books.service.ts file in the src directory. Write the below lines of code in the file
// src/books/books.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { Book } from '../book.model';
@Injectable()
export class BooksService {
private books: Book[] = [
{ id: 1, title: 'Book 1', author: 'Author 1', description: 'Description for Book 1' },
{ id: 2, title: 'Book 2', author: 'Author 2', description: 'Description for Book 2' },
{ id: 3, title: 'Book 3', author: 'Author 3', description: 'Description for Book 3' }
];
;
async getAllBooks(): Promise<Book[]> {
return this.books;
}
async getBookById(id: number): Promise<Book> {
const book = this.books.find(book => book.id === id);
if (!book) {
throw new NotFoundException('Book not found');
}
return book;
}
async createBook(bookData: Book): Promise<void> {
this.books.push({ ...bookData, id: this.generateId() });
}
async updateBook(id: number, updatedBookData: Book): Promise<void> {
const index = this.books.findIndex(book => book.id === id);
if (index === -1) {
throw new NotFoundException('Book not found');
}
this.books[index] = { ...this.books[index], ...updatedBookData };
}
async deleteBook(id: number): Promise<void> {
const index = this.books.findIndex(book => book.id === id);
if (index === -1) {
throw new NotFoundException('Book not found');
}
this.books.splice(index, 1);
}
private generateId(): number {
return this.books.length > 0 ? Math.max(...this.books.map(book => book.id)) + 1 : 1;
}
}
In above BooksService, we have the following methods:
These methods handle the business logic for managing books and interact directly with the in-memory JSON structure to perform CRUD operations.
领英推荐
Create a Controller:
As we already know Controllers in Nest.js are responsible for handling incoming HTTP requests and returning responses. You can create a new controller using the Nest CLI command as given below:
nest generate controller <controllerName>
Inside your controller, define methods to handle different HTTP methods (GET, POST, PUT, DELETE) and map them to specific routes.
Let's create a controller books by using Nest CLI command as shown below
nest generate controller books
This will create a books.controller.ts file in the src directory. Update it with the following code:
// src/books/books.controller.ts
import { Controller, Get, Post, Put, Delete, Param, Body, NotFoundException } from '@nestjs/common';
import { BooksService } from './books.service';
import { Book } from './book.model';
@Controller('books')
export class BooksController {
constructor(private readonly booksService: BooksService) {}
@Get()
async getAllBooks(): Promise<Book[]> {
return this.booksService.getAllBooks();
}
@Get(':id')
async getBookById(@Param('id') id: string): Promise<Book> {
const book = await this.booksService.getBookById(Number(id));
if (!book) {
throw new NotFoundException('Book not found');
}
return book;
}
@Post()
async createBook(@Body() bookData: Book): Promise<void> {
await this.booksService.createBook(bookData);
}
@Put(':id')
async updateBook(@Param('id') id: string, @Body() updatedBookData: Book): Promise<void> {
await this.booksService.updateBook(Number(id), updatedBookData);
}
@Delete(':id')
async deleteBook(@Param('id') id: string): Promise<void> {
await this.booksService.deleteBook(Number(id));
}
}
In above BooksController, we have the following methods:
These methods delegate the actual business logic to the BooksService, which is responsible for interacting with the data source (in-memory JSON structure in this case) and performing the necessary operations.
After implementing the controller and service files our project directory looks like
Run Your Application:
With your API endpoints defined, you can now start your Nest.js application and test your API using tools like Postman or curl. Use the command npm run start:dev to start your application in development mode as shown below
npm run start:dev
Once our Nest.js application starts successfully!!! you will see the below screen in console
Note: By default Nest.js application runs on port number 3000.
Awesome!, Finally we created a REST API using Nest.js, Let's test our api using Postman. As our book management api uses in-memory db let's create a book record in our db using the below curl :
curl --location 'https://localhost:3000/books' \
--header 'Content-Type: application/json' \
--data '{
"id": 101,
"title": "Introduction to NestJS",
"author": "Anonymous",
"Description": "This book helps people to learn NestJS"
}'
Now let's try retrieving the book using curl
curl --location 'https://localhost:3000/books/1'
The above curl will give output something like below
{
"id": 1,
"title": "Book 1",
"author": "Author 1",
"description": "Description for Book 1"
}
Note: you can make use of Postman in order to test the other methods like update, delete & list all books routes of the above api yourself.
Now, you might be asking yourself: 'With so many JavaScript frameworks available for creating REST APIs, why should I choose Nest.js?' Let's dive into this question together and explore what sets Nest.js apart from the rest.
Why Choose Nest.js for REST API Development:
With numerous JavaScript frameworks available for building RESTful APIs, choosing the right one can be a daunting task. However, Nest.js stands out among them for several compelling reasons:
As now you are aware about different offerings of Nest.js , it's best time to ask you a question ie
When to Choose Nest.js:
You should consider using Nest.js in below scenarios
That's all for this article . If you found this article insightful and want to stay updated on more content like this, be sure to follow me for future articles on Nest.js, TypeScript, and other cutting-edge technologies. Let's continue this journey together as we explore the endless possibilities of modern web development. Thank you for your support and happy coding! ??