Building a Scalable REST API with NestJS and Prisma
In this tutorial, we’ll explore how to create a scalable REST API using NestJS and Prisma. We’ll start by introducing the basics of NestJS and Prisma, then dive into creating a new project, setting up Prisma, and defining a database schema.
What is Prisma?
Prisma is a next-generation Node and TypeScript object-relational mapper (ORM) that provides a powerful database toolkit for building scalable and maintainable applications. With Prisma, you can define your data models and relations in a declarative way, making it easier to work with your database.
Why Use Prisma?
Prisma improves type safety by simplifying database access and reducing repetitive CRUD boilerplate. It’s easy to integrate with your preferred framework and is an ideal database toolkit for creating dependable and scalable web APIs.
Creating a New NestJS Project
To get started, make sure you have Node.js (≥v10.13.0, except for v13) installed, as well as Postman. Then, install the Nest CLI using the following command:
npm install -g @nestjs/cli
Once installed, create a new Nest project using the following command:
nest new my-nest-project
Choose npm as the preferred package manager and hit Enter.
Setting up Prisma
Install the Prisma CLI as a development dependency using the following command:
npm install --save-dev prisma
Then, invoke the Prisma CLI locally using npx:
npx prisma
Create your initial Prisma setup using the Prisma init command:
npx prisma init
This will create a new Prisma directory with the following files:
schema.prisma
: specifies your database connection and contains the database schema.env
: a dotenv file typically used to store your database credentials in a group of environment variables
Connecting to a Database
For this tutorial, we’ll connect to an SQLite database. Open the datasource/schema.prisma
file and update the content with the following code:
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
Then, modify the .env
file to specify the location of the database file:
DATABASE_URL="file:./dev.db"
Defining a Database Schema
Define a Todo schema in the schema.prisma
file:
model Todo {
id Int @id @default(autoincrement())
title String
completed Boolean @default(false)
}
Generate your SQL migration files and run them against the database using the following command:
npx prisma migrate dev
Setting up Prisma Client
Install Prisma Client using the following command:
npm install @prisma/client
Create a prisma.service
file in the src
folder to abstract away the Prisma Client API for database queries:
“`
import { PrismaClient } from ‘@prisma/client’;
@Injectable()
export class PrismaService {
private readonly prisma: PrismaClient;
constructor() {
this.prisma = new PrismaClient();
}
async findAllTodos(): Promise async createTodo(todo: Todo): Promise async updateTodo(id: number, todo: Todo): Promise async deleteTodo(id: number): Promise Generate a Todo module using the following command: @Injectable() async findAllTodos(): Promise async createTodo(todo: Todo): Promise async updateTodo(id: number, todo: Todo): Promise async deleteTodo(id: number): Promise Test the application using Postman. Send a GET request to That’s it! You’ve now built a scalable REST API using NestJS and Prisma.
return this.prisma.todo.create({
data: todo,
});
}
return this.prisma.todo.update({
where: { id },
data: todo,
});
}
await this.prisma.todo.delete({
where: { id },
});
}
}
“`
Generating a Todo Module
nest generate module todo
Then, generate a service file for the Todo module:
nest generate service todo
Update the todo.service
file with the following code:
“`
import { Injectable } from ‘@nestjs/common’;
import { PrismaService } from ‘./prisma.service’;
export class TodoService {
constructor(private readonly prisma: PrismaService) {}
return this.prisma.createTodo(todo);
}
return this.prisma.updateTodo(id, todo);
}
await this.prisma.deleteTodo(id);
}
}
“`
Testing the Applicationhttp://localhost:3000/todos
to retrieve all todos. Send a POST request to http://localhost:3000/todos
to create a new todo. Send a PUT request to http://localhost:3000/todos/:id
to update a todo. Send a DELETE request to http://localhost:3000/todos/:id
to delete a todo.