Sitemap

Unlocking the Power of Nest JS: A Simple Guide to API Implementation

3 min readJun 27, 2023

Introduction

Welcome to this learn-by-doing article where you will learn the ins and outs of implementing a REST API using the powerful Nest JS framework. As we delve into the realm of server-side data handling, you’ll discover how this API serves as a seamless communication bridge between client applications, be it web or mobile. By leveraging the TypeScript-based Nest JS framework, we can tap into the vast possibilities offered by object-oriented programming (OOP) concepts. In this tutorial, we will embark on an exciting journey to create a simple yet robust API tailored specifically for bookmark management.

Module Structure: To ensure modularity and maintainability, we are implementing this API as a separate module. Let’s take a closer look at the file structure of this module, which is outlined below:

file structure of the module

DTO Creation: To facilitate smooth data transfer between the client and server, I’ve started by creating two Data Transfer Objects (DTOs): create-bookmark.dto.ts and edit-bookmark.dto.ts. These DTOs define the structure and validation rules for creating and editing bookmarks respectively. Take a look at the code snippet below to see how they are implemented:

import { IsNotEmpty, IsOptional, IsString } from "class-validator";

export class CreateBookMark {
@IsString()
@IsNotEmpty()
title: string;

@IsString()
@IsOptional()
description?: string;

@IsString()
@IsOptional()
link?: string;
}

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------

import { IsNotEmpty, IsNumber, IsOptional, IsString } from "class-validator";
import { CreateBookMark } from "./create-bookmark.dto";

export class EditBookMark extends CreateBookMark{
@IsNumber()
@IsNotEmpty()
id: number;
}

Validation with class-validator: To streamline the validation process and uphold data integrity, we make use of the class-validator library. This powerful library provides convenient facilities for validating the members of our models and maintaining the defined constraints.

By utilizing decorators, we can easily enforce various validation rules on our model properties.

Controller Implementation: Handling HTTP Requests, To process incoming HTTP requests and provide the corresponding responses, we need to implement our controller class. In this case, our API endpoint is designed to retrieve all the data related to a specific request. Let’s take a look at the implementation:

complete implementation BookmarkController

import { Controller, Get, HttpCode, HttpStatus } from '@nestjs/common';
import { BookmarkService } from './bookmark.service';


@Controller('bookmark') // Decorator to identify controller
export class BookmarkController {
constructor(
private bookmarkService: BookmarkService // Handel the logic related to APIs
) {

}

@HttpCode(HttpStatus.OK)
@Get('get-all')
getBookMarks(
) {
return this.bookmarkService.getBookMarks();
}
}

In the provided code snippet, there are several decorators used for processing and defining the behavior of the API endpoint. Let’s explore the most significant ones:

@Controller('bookmark')

  • This decorator is used to identify the controller class and set the base path for all the routes defined within the controller

@HttpCode(HttpStatus.OK)

  • This decorator sets the HTTP response status code for the route handler to 200 (OK).

@Get('get-all')

  • This decorator specifies the HTTP request method as GET and sets the route path /get-all relative to the base path defined in the controller.

Service Explanation: The service layer in NestJS handles the business logic of the functionality and serves as an intermediary between the controller and the database. Let’s explore how the service retrieves data from the database and organizes it according to a standard format, using the example of the “get all” API.

complete implementation of BookMarkService

import { Injectable } from '@nestjs/common';
import { CreateBookMark, EditBookMark } from './dto';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class BookmarkService {

constructor(private prismaService: PrismaService) {

}

async getBookMarks(
) {
try {
const bookmarks = await this.prismaService.bookmark.findMany();
if (!bookmarks.length) {
throw Error("No bookmarks found")
}
return { status: true, data: bookmarks };
} catch (error) {
throw error;
}
}
}

In this particular service, data is retrieved from the database using the Prisma ORM (Object-Relational Mapping) and returned in JSON format.

The behavior of Prisma within the Nest JS framework is an interesting topic that can be explored in a dedicated feature article. Let’s take a high-level overview: Prisma is a powerful ORM that simplifies database access and manipulation by providing a type-safe and intuitive API.

By further exploring the numerous features and capabilities of Nest JS in the context of REST API development, developers can unlock the full potential of this framework and leverage it to build powerful and scalable applications.

Happy Coding!

--

--

Kasun Abaywardana
Kasun Abaywardana

Written by Kasun Abaywardana

Kasun Abaywardana: 7+ yrs software dev exp. JS specialist in React, Node, Angular, MongoDB. Passionate about creating innovative solutions.

No responses yet