DEV Community

Fernando
Fernando

Posted on

Learning to build an API in NestJS (Node + Typescript)

This is the first article of a series I'll be posting as an exercise for learning and digesting knowledge. Not just for me, but for other people that already have some coding experience on MVC projects but never built an API in Typescript.

If you want to dive into the "tutorial", skip the "My approach" section. However, I highly recommend you read it, to find out if my approach is what you are looking for and to get a sense of the prerequisites to follow along.

What this article will dive into

Scaffolding a NestJS App, Modules, and Controllers. If you don't know what those are, you will find out throughout this article.

My approach (given my context and background)

First, the premises which resulted in this (and the following posts), then I'll tell you my full background.

INITIAL DESIRE: Learn Typescript and use it to build an API

THE RESULTING GOAL: Build an API with NestJS understanding its modules, controllers, and services architecture.

My Background

I learned Web development working in a "Software Factory". The main programming language was C# in .Net Core and Entity Framework. I still work there and still code, but since I managed to get a grip on the coding part and the company's methodologies and architectures, my role changed to be more of a tech/team leader helping other new developers and noodling with the project management tasks. I am closing on three years of working here.

I still love coding and I would like to work on side projects with friends and colleagues. I love .Net Core. But I feel like I should know to build apps with other technologies. Not just to know more and get more coding skills. But to have a better understanding of other technologies so that I can better lead my teams and, last but not least, embark yet again on a learning journey that stimulates my brain cells.

Research building up to this story/tutorial.

First of all, I needed to learn typescript. So I looked at some youtube tutorials. If you know Javascript (like in my case), you need a quick tutorial teaching you the basics. Free Code Camp has great tutorials. I watched this one.

I found that NestJs is a mainstream framework for building APIs with typescript... So that seemed to be the no-brainer. It builds on top of Express, which is a framework I noodled on a bit at some point when I touched the surface of Node. I like to get the big picture of what I am going to do, so I worked along yet another YouTube video to build my first ever NestJs API. Now I want to really understand what is happening so that I can leverage this tool with my previously gained knowledge of building apps in .Net Core.

Enough about me. Let's dive into this story...

Ready, set, go be a noob... 😘

Startup

Begin with the official NestJs documentation which really talks about basic stuff: docs.

Go to the folder where you save all your projects and open a terminal there. Then run these commands to scaffold the NestJS project:

$ npm i -g @nestjs/cli
$ nest new project-name
Enter fullscreen mode Exit fullscreen mode

The main.ts file is the one that holds the code for starting up the server. To keep things as familiar as possible, configure what Nest uses under the hood to be Express. That is done by importing the corresponding class and passing it to the create method of Nest.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  await app.listen(3000);
}
bootstrap();
Enter fullscreen mode Exit fullscreen mode

You can run this basic app and access it on your browser at port 3000: $ npm run start

Taking a look at this main.ts file, we see there is a reference to an AppModule. So, what is it?

What are Modules?

Reading the docs, it seems like a Module is a structure that encapsulates and isolates functionality from another. It flirts with the microservice concept. If you are used to building classic layered applications, you usually scaffold an application layer, a business logic layer, a services layer, and a data access layer for example. The NestJs approach may be a little weird when you try to do some things the way you are used to. I will give you two examples:

  1. If you try to replicate a typical application layer where you group all your controllers in a "Controllers" folder. This NestJs Module concept kind of throws that away. Obviously, you can do whatever you want... You could have just an AppModule with a hundred controllers and that's it...
  2. If you try to implement a data access layer which is common for all the apps. That layer can be thought of as a module in itself. Clearly, not every module has to have controllers in it and you can place them in whatever folder you choose. Just decide which folder structure that soothes your mind.

Sticking with the NestJs way, let's leave that AppModule in peace and use it to bring together every other module that hopefully will be created by the end of this journey.

A Module is declared by decorating the Module's main class.

import { Module } from '@nestjs/common';
@Module({})
export class YourModule{}
Enter fullscreen mode Exit fullscreen mode

The naming convention for this file is [module name].module.ts

Now that we declared the module, we should specify the things that this module provides to the app and also what it needs to work properly. This is defined on the object passed to the @Module decorator: controllers, providers, imports, and exports.

import { Module } from '@nestjs/common';
@Module({
  imports: [],
  controllers: [],
  providers: [],
  exports: []
})
export class YourModule{}
Enter fullscreen mode Exit fullscreen mode

Of those 4 concepts, the only one that looks familiar is the controller. Let's start with that.

Controllers

A Controller is a class responsible for defining endpoints (path + handler method) that will process the incoming requests when the routing is set up. As with Modules, we need to decorate the class.

import { Controller, Get } from '@nestjs/common';

@Controller('your-controller')
export class YourController {
  constructor() {}

  @Get('say-hello')
  getHello(): string {
    return "Hello";
  }
}
Enter fullscreen mode Exit fullscreen mode

Also, the controller endpoints should be decorated with the HTTP verb. The path is the result of combining what you define in the controller decorator and the HTTP verb decorator. This example defines an endpoint that routes to the path GET /your-controller/say-hello and returns a string "Hello".

You can access request properties by adding decorators to the method parameters. You need this to populate your parameters correctly, whether they come from the query parameters, the request body, or some URL-embedded parameter.

This way of deserializing the request is a bit lengthy for me, compared to my beloved .Net Core ❤️.

When you finish setting up your controller and endpoint, it should be included as a controller of some module. If not, NestJs does not know that this controller exists and the routing can not be done.

Wrap Up

These are the real basics for launching a local API with NestJs. We covered Controllers, Modules, and Providers. My brain is burning right now, so I think this is a good time to stop.

In the next article, we will try to interact with our API through GET, POST, PUT and DELETE endpoints. This will require parsing incoming requests, fetching data, and more. Surely we will need some service...

Here is me coding literally after I wrote this article. All the mistakes, errors, and distractions. No edit:

Top comments (6)

Collapse
 
mauro_codes profile image
Mauro Garcia

As someone with experience working with Angular in the past, Nest looks so familiar! An excellent choice if you want to build your API with a similar dev experience that you get with Angular in the front. I had heard about Nest a million times before, but I needed to take the time to understand what it was about. So, thanks for this article Fer! It helped a lot!

Collapse
 
fekabas profile image
Fernando

I was planning on building a ReactJS frontend for this NestJS API. But now that you mention Angular is similar, maybe I should try it!

Glad this article was helpful! The next one is just around the corner. Stay tuned!

Collapse
 
kostyatretyak profile image
Костя Третяк

Ditsmod is even more reminiscent of Angular because it relies heavily on Dependency Injection, which was just extracted from Angular 4.4.7.

Collapse
 
sorasan profile image
Diego Fernando Mera Largo

wow, looks interesting! rigth now i'm leaning fastAPI which it is a framework to build API in python, it looks way moooooore easy than nestJs but it still looking cool

Collapse
 
fekabas profile image
Fernando

Cool! Seems it is pretty quick to build an API with fastAPI, isn't it? Maybe I'll try it after NestJS.

Collapse
 
sorasan profile image
Diego Fernando Mera Largo

it is indeed :D maybe you will able to build an API faster because of its easy sintax and learning curve