Building Powerful REST APIs with Node.js, Prisma ORM, and PostgreSQL

Get ready to master the art of building APIs that will be the backbone of your applications. By harnessing the power of Node.js, Prisma ORM, and Postgres, you’ll be well on your way to crafting exceptional user experiences.

Let’s embark on this exciting journey together!

Here’s what we’ll be exploring:

  • Node.js in Action: We’ll unveil the magic of Node.js, the JavaScript runtime environment that excels at building lightning-fast and scalable APIs.
  • Prisma ORM: The Database Simplifier: Dive into Prisma ORM, the game-changer that simplifies complex database interactions with Postgres. Say goodbye to tedious SQL queries!
  • Postgres: The Powerhouse Database: We’ll unlock the potential of Postgres, the feature-rich open-source relational database that provides a solid foundation for your APIs.
  • REST API Fundamentals and Beyond: We’ll break down the core concepts of REST APIs and guide you through designing, developing, and deploying APIs that are efficient and user-friendly.

Project Setup and Installation

1. Package Installation

Npm i prisma express ts-node typescript @prisma/client

2. Script to Start the Dev Server

"Dev":"nodemon index.ts"

Setup Prisma in Node Project

1. Using the Prisma CLI, we can add Prisma to our Node project. Use the following command.

Npx prisma init –datasource-provider postgresql

You may add a database here by using the –datasource-provider flag. I’m using a PostgreSQL database as an example, but you can use any database that Prisma supports.

The.env file and the Prisma folder, which contains your migration files, are the first two files that Prisma will generate in your project when you run the aforementioned instruction.

Inside the .env file, there is one key called DATABASE_URL you need to add your database url there.

Inside the Prisma folder, you will get a schema.prisma file inside which you can add your database models and structure.

Database Model

Let’s create a database schema inside prisma.schema file:

We’ll use a user and post example where the user can have numerous posts, essentially a one-to-many relationship.

generator client {
 provider = "prisma-client-js"
}

datasource db {
 provider = "postgresql"
 url = env("DATABASE_URL")
}

model User {
 id String @id @default(uuid())
 email String @unique
 name String
 role ROLE @default(USER)
 posts Post[]
}

model Post {
 id String @id @default(uuid())
 user User @relation(fields: [authorId], references: [id])
 authorId String
 title String
 published Boolean @default(false)
 createdAt DateTime @default(now())
 updatedAt DateTime @updatedAt
}

enum ROLE {
 USER
 ADMIN
}

Related read: Mastering Prisma ORM in Node.js: A Comprehensive Guide

Start Building Robust REST APIs with Node.js, Prisma ORM, and Postgres Today

Run Migration Command

Npx prisma migrate dev -name "schema-creation"

This command will create a migration file inside prisma/migrations folder with the name “schema-creation” and then execute the migration.

Let’s start with creating some endpoints and running SQL queries on our database using Prisma.

import { PrismaClient } from "@prisma/client";
import express from "express";

const prisma = new PrismaClient();
const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

//Add user
app.post("/add-user", async (req, res) => {
 const user = await prisma.user.create({
  data: {
   email: req.body.email,
   name: req.body.name,
  },
 });
 res.json(user);
});

//Add Post
app.post("/add-post", async (req, res) => {
 const data = await prisma.post.create({
  data: {
   title: req.body.title,
   authorId: req.body.authorId,
  },
 });
 res.json(data);
});

//Get users
app.get("/users", async (req, res) => {
 const data = await prisma.user.findMany();
 res.json(data);
});

//Get post
app.get("/posts", async (req, res) => {
 const data = await prisma.post.findMany();
 res.json(data);
});

//Update user
app.put("/update-user", async (req, res) => {
 const data = await prisma.user.update({
  data: {
   name: req.body.name,
 },
 where: {
  email: req.body.email,
 },
 });
 res.json(data);
});

//Delete post
app.delete("/delete-post", async (req, res) => {
 const data = await prisma.post.delete({
  where: {
   id: req.body.id,
  },
 });
 res.json(data);
});

app.listen(3000, () => {
 console.log("Server running 3000");
});
coma

Conclusion

In essence, Node.js, Prisma, and PostgreSQL form a powerful synergy for crafting RESTful APIs. Node.js’s asynchronous nature makes it ideal for handling numerous API requests efficiently. Prisma acts as an elegant abstraction layer, streamlining interaction with the PostgreSQL database. PostgreSQL itself boasts robust features and security for managing your application’s data.

This combination empowers you to streamline development, concentrate on core functionalities, and construct robust APIs that seamlessly handle data interactions for your web application. Equipped with this knowledge, you’re prepared to create modern, scalable APIs that fuel your upcoming project.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?