NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It leverages TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Reactive Programming). This tutorial guides you through creating your first REST API using NestJS, TypeScript, and Node.js.

Prerequisites

  • Node.js installed (version 14 or higher)
  • npm or yarn package manager
  • Basic knowledge of TypeScript and JavaScript
  • Text editor or IDE (Visual Studio Code recommended)

Setting Up the Project

Start by creating a new NestJS project using the Nest CLI. Open your terminal and run:

npm i -g @nestjs/cli

Then create a new project:

nest new my-first-api

Navigate into your project directory:

cd my-first-api

Creating a REST Endpoint

Generate a new controller to handle HTTP requests:

nest generate controller users

Implement the Controller

Open src/users/users.controller.ts and modify it as follows:

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

@Controller('users')

export class UsersController {

@Get()

findAll(): string {

return 'This action returns all users';

}

}

Test the API

Start the development server:

npm run start

Open your browser and navigate to:

http://localhost:3000/users

You should see the message: This action returns all users.

Adding Data with POST

Generate a new service to handle data logic:

nest generate service users

Update the Service

Open src/users/users.service.ts and add a simple data store:

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

@Injectable()

export class UsersService {

private users = [];

create(user: any) {

this.users.push(user);

return user;

}

findAll() {

return this.users;

}

}

Update the Controller to Handle POST

Modify src/users/users.controller.ts to include POST method:

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

@Controller('users')

export class UsersController {

constructor(private readonly usersService: UsersService) {}

@Get()

findAll(): string {

return 'This action returns all users';

}

@Post()

create(@Body() user: any) {

return this.usersService.create(user);

}

}

Summary

In this tutorial, you learned how to set up a NestJS project, create a REST API with GET and POST endpoints, and handle data using services. NestJS provides a structured and scalable way to build server-side applications with TypeScript and Node.js.

Continue exploring NestJS features like middleware, guards, and database integration to build more complex and secure APIs.