3-how-to-create-scalable-apis-with-nestjs-and-postgresql.html

How to Create Scalable APIs with NestJS and PostgreSQL

In today’s digital landscape, building scalable APIs is essential for any application that demands robust performance and seamless user experiences. NestJS, a progressive Node.js framework, paired with PostgreSQL, an advanced relational database, offers a powerful combination for developing scalable APIs. In this article, we’ll dive into the essential steps and best practices to create scalable APIs using these technologies.

Understanding NestJS and PostgreSQL

What is NestJS?

NestJS is a framework built on top of Node.js, designed to help developers create efficient, reliable, and scalable server-side applications. It utilizes TypeScript, which enhances code quality and maintainability, making it an excellent choice for large-scale applications. The modular architecture of NestJS promotes code reusability and separation of concerns, which are critical for scalability.

What is PostgreSQL?

PostgreSQL is an open-source relational database management system known for its robustness, scalability, and compliance with SQL standards. It supports advanced data types and performance optimization features, making it a preferred choice for applications that require complex queries and data integrity.

Use Cases for Scalable APIs

  • E-commerce Platforms: Handling thousands of concurrent users and transactions.
  • Social Media Applications: Managing large volumes of user-generated content.
  • Data-Driven Applications: Processing and analyzing large datasets in real-time.

Setting Up the Environment

Before diving into the code, let’s set up our development environment. We’ll need Node.js, NestJS CLI, and PostgreSQL installed on your machine.

Step 1: Install Node.js

Download and install Node.js from the official website. Ensure you have the latest version for optimal performance.

Step 2: Install NestJS CLI

Open your terminal and run the following command to install the NestJS CLI globally:

npm install -g @nestjs/cli

Step 3: Set Up PostgreSQL

Follow the instructions on the PostgreSQL website to install PostgreSQL. After installation, create a new database for your project:

CREATE DATABASE my_api_db;

Creating a NestJS Project

Step 4: Initialize a New Project

Run the following command to create a new NestJS project:

nest new scalable-api

Change into the project directory:

cd scalable-api

Step 5: Install Required Dependencies

You will need to install the following packages for PostgreSQL integration:

npm install @nestjs/typeorm typeorm pg

Configuring TypeORM with PostgreSQL

Step 6: Set Up TypeORM Configuration

Open the app.module.ts file and configure TypeORM to connect to your PostgreSQL database.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { User } from './user.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'your_username',
      password: 'your_password',
      database: 'my_api_db',
      entities: [User],
      synchronize: true, // Use with caution in production
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Step 7: Create an Entity

Entities represent database tables in TypeORM. Let’s create a simple User entity. Create a new file named user.entity.ts:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}

Building the User Module

Step 8: Create the User Module

Generate a user module, service, and controller using the NestJS CLI:

nest generate module users
nest generate service users/users
nest generate controller users/users

Step 9: Implement the User Service

Open the users.service.ts file and implement the basic CRUD operations:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  create(user: User): Promise<User> {
    return this.usersRepository.save(user);
  }

  findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  findOne(id: number): Promise<User> {
    return this.usersRepository.findOneBy({ id });
  }

  async remove(id: number): Promise<void> {
    await this.usersRepository.delete(id);
  }
}

Step 10: Implement the User Controller

Now, let’s expose our service methods through the controller. Open users.controller.ts and add the following code:

import { Controller, Get, Post, Body, Param, Delete } from '@nestjs/common';
import { UsersService } from './users.service';
import { User } from './user.entity';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  create(@Body() user: User) {
    return this.usersService.create(user);
  }

  @Get()
  findAll() {
    return this.usersService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.usersService.findOne(+id);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.usersService.remove(+id);
  }
}

Testing the API

Step 11: Run the Application

Start the NestJS application:

npm run start

Step 12: Use Postman or cURL

You can now test your API using Postman or cURL. Here are some example requests:

  • Create a User:
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com"}'
  • Get All Users:
curl http://localhost:3000/users

Conclusion

Building scalable APIs with NestJS and PostgreSQL is a powerful approach that leverages the strengths of both technologies. By following the steps outlined in this guide, you can create a robust API ready to handle the demands of modern applications. Focus on modular design, efficient database interactions, and thorough testing to ensure your API remains scalable and maintainable as it grows. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.