creating-restful-apis-with-nestjs-and-postgresql.html

Creating RESTful APIs with NestJS and PostgreSQL

In today's digital landscape, building robust and efficient APIs is essential for modern web applications. When it comes to developing a RESTful API, NestJS paired with PostgreSQL stands out as a powerful combination. In this article, we will explore the fundamentals of creating RESTful APIs using NestJS, a progressive Node.js framework, along with PostgreSQL, a powerful relational database. Whether you're a seasoned developer or just starting, this guide will provide you with actionable insights, step-by-step instructions, and clear code examples.

What is NestJS?

NestJS is a framework for building efficient and scalable server-side applications. It leverages TypeScript and incorporates design patterns like Dependency Injection, making it a great choice for enterprise-level applications. NestJS promotes modular development, encouraging developers to organize their codebase into modules, controllers, and services.

What is PostgreSQL?

PostgreSQL is an advanced, open-source relational database management system (RDBMS) known for its robustness, extensibility, and compliance with SQL standards. It supports complex queries, transactions, and a variety of data types, making it an excellent choice for applications that require reliable data management.

Use Cases for RESTful APIs

RESTful APIs serve as the backbone of many web and mobile applications. Here are a few common use cases:

  • Data Retrieval: APIs allow applications to access and manipulate data stored in a database.
  • Microservices Architecture: RESTful APIs enable different services to communicate and collaborate within a distributed system.
  • Third-Party Integrations: APIs facilitate connections between different software systems, allowing them to work together seamlessly.

Setting Up the Environment

Before we dive into coding, let’s set up our development environment.

Prerequisites

  • Node.js installed on your machine.
  • PostgreSQL installed and running.
  • Basic knowledge of TypeScript and RESTful principles.

Step 1: Initialize a New NestJS Project

To get started, create a new NestJS project using the Nest CLI. Open your terminal and run the following command:

npm i -g @nestjs/cli
nest new project-name

This will create a new folder with a basic NestJS structure.

Step 2: Install Required Packages

Next, navigate to your project directory and install the necessary packages to interact with PostgreSQL:

cd project-name
npm install @nestjs/typeorm typeorm pg

Step 3: Configure PostgreSQL Connection

Open the app.module.ts file and configure the TypeORM module 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'; // import your entity

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

Step 4: Create a New Entity

Entities in TypeORM are classes that represent database tables. Let’s create a User entity:

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

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

  @Column()
  name: string;

  @Column()
  email: string;

  @Column()
  password: string;
}

Step 5: Create a User Module, Service, and Controller

Next, let’s create a User module to handle our user-related operations.

nest generate module user
nest generate service user
nest generate controller user

Step 6: Implement CRUD Operations

Open the user.service.ts file to implement the CRUD operations.

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

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

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

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

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

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

Step 7: Create RESTful Endpoints

Now, open the user.controller.ts file to define the RESTful endpoints.

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

@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

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

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

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

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

Step 8: Testing the API

Run your NestJS application:

npm run start

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

  • Create a user: http POST /users { "name": "John Doe", "email": "john@example.com", "password": "securepassword" }

  • Retrieve all users: http GET /users

  • Retrieve a specific user: http GET /users/1

  • Delete a user: http DELETE /users/1

Conclusion

Creating RESTful APIs with NestJS and PostgreSQL is a straightforward process that combines the power of modern frameworks with reliable databases. By following the steps outlined in this guide, you can build a fully functional API that handles CRUD operations effectively. Whether you're developing a new application or integrating with existing services, this architecture provides a scalable solution to meet your needs. 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.