Skip to content

Instantly share code, notes, and snippets.

@Muzammil-Bilwani
Created February 11, 2025 06:58
Show Gist options
  • Save Muzammil-Bilwani/2835cbd15ab8221d5a1112ae1654a73a to your computer and use it in GitHub Desktop.
Save Muzammil-Bilwani/2835cbd15ab8221d5a1112ae1654a73a to your computer and use it in GitHub Desktop.
NestJS with TypeScript: Building a Simple API

🚀 NestJS with TypeScript: Building a Simple API

1️⃣ Install NestJS CLI (If not already installed)

Run the following command in your terminal:

npm install -g @nestjs/cli

2️⃣ Create a New NestJS Project

Create a new NestJS application:

nest new my-api

Navigate to the project directory:

cd my-api

3️⃣ Generate a Resource (Controller, Service, and Module)

nest generate resource users

This will create the necessary files in src/users/.

4️⃣ Define API Endpoints in the Controller

Edit src/users/users.controller.ts:

import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';

// The @Controller decorator marks this class as a controller
// 'users' defines the route prefix for this controller
@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  // The @Post decorator marks this as a POST endpoint
  // @Body() extracts the request body and maps it to CreateUserDto
  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
  }

  // The @Get decorator marks this as a GET endpoint
  // This retrieves all users
  @Get()
  findAll() {
    return this.usersService.findAll();
  }

  // The @Get(':id') decorator defines a dynamic route parameter
  // @Param('id') extracts the id parameter from the URL
  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.usersService.findOne(id);
  }
}

5️⃣ Define the User Service

Modify src/users/users.service.ts:

import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';

// The @Injectable decorator marks this class as a service
// This allows it to be injected as a dependency
@Injectable()
export class UsersService {
  private users = [];

  // Method to create a new user
  create(createUserDto: CreateUserDto) {
    const newUser = { id: Date.now().toString(), ...createUserDto };
    this.users.push(newUser);
    return newUser;
  }

  // Method to retrieve all users
  findAll() {
    return this.users;
  }

  // Method to retrieve a single user by ID
  findOne(id: string) {
    return this.users.find(user => user.id === id);
  }
}

6️⃣ Define a DTO (Data Transfer Object) for User Creation

Create src/users/dto/create-user.dto.ts:

// DTO ensures data validation and type safety
export class CreateUserDto {
  name: string;
  email: string;
}

7️⃣ Start the API Server

Run the server in development mode:

npm run start:dev

8️⃣ Test the API

You can test the API using Postman, cURL, or any REST client:

Create a User

POST /users
Content-Type: application/json
{
  "name": "Alice",
  "email": "[email protected]"
}

Get All Users

GET /users

Get a User by ID

GET /users/:id

🎉 Congratulations! You've successfully built a simple API using NestJS and TypeScript!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment