Build a REST API from scratch using NestJS

Image for post
Image for post

What is NestJS?

Installing NestJS

npm i -g @nestjs/cli

Create a new project

nest new project-name
git clone https://github.com/nestjs/typescript-starter.git project
cd project
npm install
npm i --save @nestjs/core @nestjs/common rxjs reflect-metadata 

Getting Started

App Controller

App Module

Main

Let’s Code

nest g controller items

Find all items

Image for post
Image for post
Get All Items — VSCode Rest Client
Image for post
Image for post
Get Item By ID
npm start
npm run start:dev

Create Items

Image for post
Image for post
POST Endpoint Test

Create Providers

nest g service items

Wrap everything in a Module

Image for post
Image for post

Deploy MongoDB Instance

docker pull mongo
docker run -p 27017:27017 --name mongodb -d mongo

Setup Mongoose

npm install --save @nestjs/mongoose mongoose
npm install --save-dev @types/mongoose
npm install --save @nestjs/config
MONGOURI=mongodb://localhost:27017
PORT=3000

Load Port Configuration

Models

Inject Models

Using Models

Image for post
Get All Items
Image for post
Image for post
Get Item By Id
Image for post
Image for post
Post Request
Image for post
Image for post
PUT Request
Image for post
Image for post
Delete Request
Image for post
Image for post
Get All Items

Logger Service

 nest g service logger
Image for post
Image for post
Logger Test

Conclusions

Source Code

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store