Introduction to RESTful APIs with NestJS

author

by Justin Shaifer

02 min read

Aug 13, 2024

author

Share

NestJS is one of the most rapidly growing frameworks for building Node.js server-side applications. Companies such as Roche, Adidas, and Autodesk, all trust NestJS when it comes to building efficient and scalable server-side applications.

NestJS is based heavily on Angular, and uses Angular-like modules, services, controllers, pipes, and decorators. This allows NestJS to help developers create scalable, testable, loosely coupled, and easily maintainable applications. NestJS was built with TypeScript, but it can also support pure JavaScript development.

NestJS offers a level of abstraction above two very popular Node.js frameworks, either Express.js or Fastify. This means that all of the great middleware that are available for Express.js and Fastify can also be used with NestJS.

The best way to get familiar with NestJS is to build a basic RESTful API with CRUD (Create, Read, Update, and Delete) functionality. This is exactly what we'll be doing together in this article. We'll be building a simple RESTful API for a Blog, with endpoints to handle CRUD operations on blog posts.

Getting Started

Code editor

Using Visual Studio Code as a code editor can help speed up NestJS development because of its smart IntelliSense and great TypeScript support.

In Visual Studio Code, make sure that you have the following user setting by going to File / Preferences / Settings, and searching for the user setting named typescript.preferences.importModuleSpecifier. Make sure to set it to relative as seen below.

"typescript.preferences.importModuleSpecifier": "relative"

This will allow Visual Studio Code to use relative paths rather than absolute paths when auto-importing. Using absolute path imports in our application can lead to problems if and when our code ends up in a different directory.

Insomnia

Insomnia is a useful API testing tool that we will use to test the NestJS API that we will be building.

The NestJS CLI

To get started with NestJS, let's install the Nest CLI. The Nest CLI is a command-line interface tool that makes it easy to develop, and maintain NestJS applications. It allows us to run our application in development mode, and to build and bundle it for a production-ready release.

npm i -g @nestjs/cli

Creating a new NestJS project

With the Nest CLI now installed, we can use it to create a new project.

nest new rest-api

This command will create a new project directory called rest-api. It will create a base structure for our project, and add in the following core Nest files:

  • app.controller.ts: A controller with a single route.
  • app.controller.spec.ts: The controller's unit tests.
  • app.module.ts: The root module of our application.
  • app.service.ts: A service for the AppModule's business logic.
  • main.ts: The entry file of our application.

The initial project structure created by the Nest CLI encourages us to follow the common convention of keeping each module in its own directory.

Testing the sample endpoint

The installation of NestJS comes with a sample API endpoint that we can test by making a request to it. If we open app.controller.ts, we can see that there is a GET endpoint that was created for us with the @Get() decorator. It returns a 'Hello World!' string.

@Get()
getHello(): string {
  return this.appService.getHello();
}

Let's run npm run start:dev from our project folder. This will run our NestJS app in watch mode, which provides live-reload support when application files are changed.

Once NestJS is running, let's open http://localhost:3000 in our web browser. We should see a blank page with the Hello World! greeting.

We can also use API testing tools such as Insomnia to make a GET request to http://localhost:3000. We should get the same Hello World! greeting as our result.

Let's remove this endpoint since it was only added by the Nest CLI for demo purposes. Go ahead and delete app.controller.ts, app.service.ts, and app.controller.spec.ts. Also, delete all references to AppController and AppService in app.module.ts.

Creating a feature module

The architectural design of NestJS encourages feature modules. This feature-based design groups the functionality of a single feature in one folder, registered in one module. This design simplifies the codebase and makes code-splitting very easy.

Module

We create modules in NestJS by decorating a class with the @Module decorator. Modules are needed to register controllers, services, and any other imported sub-modules. Imported sub-modules can have their own controllers, and services, registered.

Let's use the Nest CLI to create the module for our blog posts.

nest generate module posts

This gives us an empty PostsModule class in the posts.module.ts file.

Interface

We will use a TypeScript interface to define the structure of our JSON object that will represent a blog post.

An interface is a virtual or abstract structure that only exists in TypeScript. Interfaces are used only for type-checking purposes by the TypeScript compiler. TypeScript interfaces do not produce any JavaScript code during the transpilation of TypeScript to JavaScript.

Let's use the Nest CLI to create our interface.

cd src/posts 
nest generate interface posts

These commands allow us to create a posts.interface.ts file in the feature-based folder for our blog posts, which is /src/posts.

The TypeScript interface keyword is used to define our interface. Let's make sure to prefix it with export to allow this interface to be used throughout our application

export interface PostModel {
  id?: number;
  date: Date;
  title: string;
  body: string;
  category: string;
}

From the command-line prompt, let's reset our current working directory back to the root folder of our project by using the following command.

cd ../..

author

Justin Shaifer

Justin Shaifer is a dedicated full-stack developer with a passion for building robust, scalable web applications. With a background in computer science and several years of experience in the tech industry, Justin excels in both front-end and back-end development. His expertise includes working with a variety of programming languages and frameworks, making him adept at tackling complex projects from conception to deployment. Justin is known for his problem-solving skills and his ability to create seamless user experiences that drive business success.

See all posts by this author