Nandhakumar's Display Picture

Nandhakumar

Nov 24, 2022

5 min read

Nest JS Tutorial #1: Create Your First API

#nestjs

#javascript

#typescript

#backend

#api

Nest JS Tutorial #1: Create Your First API

Hi There! 👋

It's been a couple of months working with Nest.JS and I love the way the framework build to develop scalable server-side applications

I am still trying to learn more about Nest.JS, So thought of sharing my learning in the form of tutorial series from Beginner to Advanced.

Let's Get Started Now! 🚀

Prerequisite

What is Nest.JS?

Nest.JS is a framework to build highly scalable Node.JS server-side applications. It comes with the full support of typescript(It also allows us to build the app with pure JS as well).

It combines OOP(Object Oriented Programming) and Functional Programming to write clean and reusable code.

If you have ever built a server-side application, you would have heard about Express.JS and Fastify libraries.

Under the hood, Nest.JS uses Express.JS as its default HTTP Server. If you prefer to use Fastify, you can switch easily (More about this on official docs)

That's a short brief on Nest.JS


Generating Nest.JS Project

Before generating the project, make sure you have installed the latest version of Node.JS on your system

I am using Node.JS Version v18.12.1

To generate a Nest.JS Project first, you need to install Nest Cli

npm i -g @nestjs/cli

Now generate a new Nest.JS project

nest new [your project name]

It will ask for,

  • Which package manager (npm, yarn, pnpm) to use? (I choose yarn, you can choose as you wish)

Now open the project on your code editor

Understanding Nest.JS Project Structure

Nest JS Project Structure
  • node_modules - Contains all the libraries that are required for your project.
  • src - Contains your application source code, Under this directory Nest.JS has generated a starter code. Let's explore what they are,
    • app.controller.spec.ts - Contains unit test cases for each controller implementation
    • app.controller.ts - Contains the implementation of the API
    • app.service.ts - Contains business logic which will be used in the controller
    • app.module.ts - Contains Imports, Exports and DI(Dependency Injection). More on this later...
    • main.ts - Contains implementation to bootstrap the application. This is the starting point of your application
  • test - Contains E2E test case implementations
  • .eslintrc.js - Contains lint configuration that helps to identify incorrect syntax, typescript standards and more ...
  • .gitignore - Contains files & directories to ignore when pushing the code to GitHub
  • .prettierrc - Contains prettier config to format your code
  • nest-cli.json - Basic Nest.JS Configuration
  • package.json - Contains dependency, scripts, project version and more required for your project
  • README.md - Contains documentation of your project
  • tsconfig.json - Contains typescript configurations

Basic Understanding Of API(You can skip this section if you know what is an API)

If you are a complete beginner in API development.

In simple terms, Let's say you have a raw cloth material and you want it to be stitched.

So you will go to a tailor and give your cloth to stitch. You will also give some instructions on how the design should be.

Considering the above example, In the computer world frontend application(Apps with user interfaces) will request certain data with some parameters(raw cloth material and instruction to design the cloth) to the server(tailor) in return server will send you the requested data as a response(stitched cloth).

These requests are sent using an API URL.

An API(Application programming interface) will look like this 👇

// Example API
"https://google.com/api/users" // returns a list of users

If you are still confused. Don't worry, going forward you will figure it out.

Creating Your First API

Let's start the server first

Open your terminal

Navigate to your project directory

And Run 👇

yarn start:dev

Replace yarn with npm or pnpm if you have configured those package managers initially

Now your server should have been started on

http://localhost:3000

To test the starter code generated by Nest.JS

Open Postman(tool to test the API)

Choose GET Method and Add the API URL(http://localhost:3000) then hit Send

API Testing With Postman

You will see the response as "Hello World!"

Great!

You have executed your first API.

Now let's try to customise this API in a way to get a list of user names

Step 1

Open app.controller.ts

  • Add /user route to @Controller() decorator
  • Change the function name under @Get() decorator to getUsers
  • Change return type from string to string[]
  • Change the App Service method name to getUsers

Code Snippet 👇


import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller('/users') // Add '/user' route
export class AppController {
constructor(private readonly appService: AppService) {}

// Change the function name to getUsers
@Get()
getUsers(): string[] { // Change return type to string[](stirng Array)
// Change the service method name to getUsers
return this.appService.getUsers();
}
}

Step 2

Open app.service.ts

  • Change the function name getHello() inside AppService Class to getUsers()
  • Change return type from string to string[]
  • Change the return value from 'Hello World!' to ['userOne','userTwo']

Code Snippet 👇

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
// Change function name to getUsers
getUsers(): string[] { // Change return type to string[](stirng Array)
return ['userOne', 'userTwo'];
}
}

That's it your user API is ready now.

Let's test it in Postman

  • Open Postman
  • Choose GET Method and Add the API URL(http://localhost:3000/users) then hit Send
Testing Get Users API Developed in Nest JS

If you got a response as a list of user names.

Congratulation! 👏

You have created your first API in Nest.JS 🙌


Thanks For Reading!

Hope you have learned something new today 😊.

I welcome your questions, feedback, and discussions on this topic. Don't hesitate to reach out if there's something you'd like to talk about.

If you find this post helpful Tweet this Post

Follow and connect with me on Twitter, Instagram, Email and LinkedIn for more interesting stuff like this.

Cheers ✌️