Delving Developer

Build a CRUD API with NestJS, Postgres & Prisma

Eddie Cunningham
Eddie Cunningham
4 min readNestJS
Cover Image for Build a CRUD API with NestJS, Postgres & Prisma

Creating a robust CRUD API is foundational for application development, and using powerful tools like NestJS, Postgres, and Prisma can make the process efficient and scalable. In this guide, we'll dive into building a CRUD API with these technologies, exploring each step to ensure that both novice and experienced developers can follow along.

NestJS: A Progressive Node.js Framework NestJS is a Node.js framework ideal for building efficient, reliable, and scalable server-side applications. Its modular architecture allows developers to organize code efficiently. NestJS supports modern JavaScript, allowing you to use TypeScript to increase code reliability and maintainability.

PostgreSQL: The Advanced Open Source Relational Database PostgreSQL, also known as Postgres, is a powerful, open-source relational database system with an emphasis on extensibility and standards compliance. It is highly stable and robust, offering extensive features that can handle complex queries and a large volume of data efficiently.

Prisma: Modern Database Toolkit Prisma is an open-source suite of tools that simplifies database workflows. It consists of Prisma Client, an auto-generated and type-safe query builder for Node.js, and Prisma Migrate for hassle-free schema migrations. Prisma integrates seamlessly with PostgreSQL, making it easier to manage database interactions.

Getting Started: Setting Up Your Environment Before starting, ensure you have Node.js and npm installed on your computer. You will also need Docker to run PostgreSQL in a container, which simplifies the setup process.

Step 1: Set Up a New NestJS Project Begin by creating a new NestJS project using the Nest CLI:

npm i -g @nestjs/cli
nest new crud-api

This will create a new NestJS application in the crud-api directory.

Step 2: Install Prisma and PostgreSQL Client Navigate into your project directory and install Prisma alongside the PostgreSQL client:

cd crud-api
npm install prisma --save-dev
npm install @prisma/client

These commands will add Prisma to your project and install the necessary client to connect to PostgreSQL.

Step 3: Configure Your Database Create a docker-compose.yml file to define a PostgreSQL service:

version: '3.8'
services:
  postgres:
    image: postgres:latest
    environment:
      POSTGRES_USER: your_username
      POSTGRES_PASSWORD: your_password
      POSTGRES_DB: your_db
    ports:
      - "5432:5432"

Start the PostgreSQL service with:

docker-compose up -d

Step 4: Initialize Prisma Prisma requires an initialization step to configure your database connection. Inside the project directory, initialize Prisma:

npx prisma init

Edit the .env file to reflect your database connection details:

DATABASE_URL="postgresql://your_username:your_password@localhost:5432/your_db?schema=public"

Step 5: Define Your Data Model In prisma/schema.prisma, define your data model:

model User {
  id       Int      @id @default(autoincrement())
  name     String
  email    String   @unique
  posts    Post[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}

Run the Prisma migrate command to create the database tables:

npx prisma migrate dev --name init

Step 6: Generate Prisma Client Automatically generate the Prisma Client tailored to your database schema:

npx prisma generate

This generates lightweight, type-safe query methods you can use in your application.

Step 7: Implement CRUD Operations In the NestJS application, create modules, services, and controllers to handle API routes. For example, a simple endpoint in users.controller.ts could be:

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

  @Get()
  async findAllUsers() {
    return this.userService.getAllUsers();
  }

  @Post()
  async createUser(@Body() userData: CreateUserDto) {
    return this.userService.createUser(userData);
  }
}

In users.service.ts, you would utilize the Prisma Client:

@Injectable()
export class UsersService {
  constructor(private prisma: PrismaService) {}

  async getAllUsers(): Promise<User[]> {
    return this.prisma.user.findMany();
  }

  async createUser(data: CreateUserDto): Promise<User> {
    return this.prisma.user.create({ data });
  }
}

Step 8: Test Your API With all components in place, start your NestJS server:

npm run start:dev

Test your API endpoints using Postman or any HTTP client of your choice.

Conclusion Building a CRUD API with NestJS, Postgres, and Prisma offers a solid foundation for scalable and maintainable applications. These tools collectively simplify backend development, enhance productivity, and improve code quality. For more advanced use-cases, consider delving deeper into NestJS modules, relationship management in Prisma, and performance tuning in PostgreSQL. These steps not only provide basic functionality but also open up the potential for implementing complex features with ease.

To learn more about NestJS, check out NestJS documentation. For Prisma, visit the official Prisma documentation, and for database optimization techniques, explore the PostgreSQL guide on indexing and performance tips.