Introduction
Building a REST API with Prisma, PostgreSQL, TypeScript, and Express is an essential skill for modern web development. With the power of Prisma ORM and PostgreSQL, you can efficiently manage data models and database queries, while TypeScript ensures type safety and scalability. In this guide, we’ll walk you through the process of setting up your environment, creating and migrating your database schema, and implementing CRUD operations for a blogging application. Additionally, you’ll learn how to leverage Express to handle API routes, making your development process faster and more efficient. Let’s dive into building a robust and scalable REST API for your app.
What is Prisma?
Prisma is an open-source tool that helps developers interact with databases more easily. It provides a set of tools for working with databases, including a query builder, migration system, and a GUI for managing data. Prisma allows developers to handle database operations without writing complex SQL code, making database workflows more efficient and intuitive.
Step 1 — Creating Your TypeScript Project
Alright, in this step, we’re going to set up a basic TypeScript project using npm. This will be the foundation for building your REST API in the tutorial. First things first, let’s create a new folder for your project. You can do this by running this command in your terminal:
$ mkdir my-blog
Now, move into that folder and initialize an empty npm project. You’ll notice that the -y flag will skip all those pesky prompts that normally pop up when you run npm init . This means npm will create the project with default settings. But, if you’re feeling adventurous and want to customize things manually, just skip the -y flag when you run the command. Here’s what you need to do next:
$ cd my-blog
$ npm init -y
Once you’ve done this, you’ll see something like this in your terminal output. It’s the default configuration of your new npm project:
Wrote to /…/my-blog/package.json:
{
“name”: “my-blog”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″
},
“keywords”: [],
“author”: “”,
“license”: “ISC”
}
Basically, this command creates a simple package.json file, which is like the instruction manual for your npm project. At this point, we’re ready to add TypeScript to your project. So, run this next command to install TypeScript, ts-node, and @types/node as development dependencies:
$ npm install typescript ts-node @types/node –save-dev
Here’s a quick breakdown of what’s happening:
- typescript : The TypeScript toolchain that will convert your TypeScript code into JavaScript.
- ts-node : This allows you to run your TypeScript code directly, without needing to first compile it to JavaScript manually.
- @types/node : This is like the Rosetta Stone for TypeScript, ensuring that TypeScript knows how to talk to Node.js and its built-in modules.
Next, let’s set up your tsconfig.json file. This file makes sure TypeScript is properly configured for your project. You can create it by running:
$ nano tsconfig.json
In the newly opened file, add this JSON code:
{
“compilerOptions”: {
“sourceMap”: true,
“outDir”: “dist”,
“strict”: true,
“lib”: [“esnext”],
“esModuleInterop”: true
}
}
After you’ve added this, save the file and close it. Now, let’s break down what this configuration does:
- sourceMap : This makes sure you can debug your TypeScript code easily by letting you trace it back to its original source in the browser or debugging tools.
- outDir : This tells TypeScript where to put the compiled JavaScript files. Here, we’ve set it to a folder named dist .
- strict : This turns on TypeScript’s strict type-checking, which helps you catch bugs earlier in development.
- lib : This includes the latest JavaScript features (think ECMAScript), so you’re all set for modern JavaScript.
- esModuleInterop : This makes it easier for TypeScript to play nice with different module systems (like CommonJS and ES Modules), which is really useful in Node.js.
This setup might be basic, but it’s a solid foundation to get you started. If you want to dive deeper into the specific settings in the tsconfig.json file, you can check out the official TypeScript documentation.
Now that your TypeScript project is ready to roll, the next step is to set up your PostgreSQL database using Docker and link it up with Prisma, a really cool ORM (Object-Relational Mapping) tool. Let’s get into that next!
Read more about setting up TypeScript projects and managing dependencies in the official guide TypeScript Configuration Options.
Step 2 — Setting Up Prisma with PostgreSQL
In this step, we’re going to install the Prisma CLI, create the first version of your Prisma schema file, set up PostgreSQL using Docker, and connect Prisma to PostgreSQL. The Prisma schema file is basically the main blueprint for your Prisma setup. It will define how your database is structured.
To start, let’s install the Prisma CLI in your project. You can do that with the following command:
$ npm install prisma –save-dev
Now, here’s a tip: It’s better to install the Prisma CLI locally in your project rather than globally. This is because if you’re working on multiple Prisma projects, having a local version of Prisma in each project avoids version conflicts. This way, each project will use its own specific version of the Prisma CLI.
Next up, we’ll set up your PostgreSQL database using Docker. You’ll need to create a docker-compose.yml file to configure and launch your database container. To make this file, run the following command:
$ nano docker-compose.yml
Then, add the following configuration inside the file:
version: ‘3.8’
services:
postgres:
image: postgres:10.3
restart: always
environment:
– POSTGRES_USER=sammy
– POSTGRES_PASSWORD=your_password
volumes:
– postgres:/var/lib/postgresql/data
ports:
– ‘5432:5432’
volumes:
postgres:
This docker-compose.yml file configures a PostgreSQL database that will run in a Docker container. It sets up the database to be accessed through port 5432. The database credentials are set as sammy for the username and your_password for the password. You can, of course, change these values to whatever you prefer. After you’re done, save the file and exit.
Now, we’re ready to launch the PostgreSQL container. To do that, run the following command:
$ docker-compose up -d
What this command does is pull the image from Docker Hub, create a container, and start the PostgreSQL database. The terminal output will look like this:
Pulling postgres (postgres:10.3)…
10.3: Pulling from library/postgres
f2aa67a397c4: Pull complete
6de83ca23e55: Pull complete
…
Status: Downloaded newer image for postgres:10.3
Creating my-blog_postgres_1 … done
To make sure everything is working, you can verify the status of your PostgreSQL container by running this command:
$ docker ps
This will show you the list of active containers. You should see your PostgreSQL container listed, along with its status and port mappings. It’ll look something like this:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8547f8e007ba postgres:10.3 “docker-entrypoint.s…” 3 seconds ago Up 2 seconds 0.0.0.0:5432->5432/tcp my-blog_postgres_1
Now that the PostgreSQL container is running, let’s move on to setting up Prisma. In your terminal, run this command to initialize Prisma in your project:
$ npx prisma init
After running this, you’ll see an output like this:
✔ Your Prisma schema was created at prisma/schema.prisma. You can now open it in your favorite editor.
Here’s a quick note: It’s a good idea to always use npx to run Prisma commands, so you’re using the version of Prisma that’s installed locally in your project. After running this command, Prisma will create a prisma folder in your project directory. Inside that folder, you’ll find the schema.prisma file, which is where your data model will go.
Along with the schema.prisma file, Prisma will also generate a .env file in the root of your project. This file will contain the environment variables for your project, including the database connection URL. To update that connection URL, open the .env file with this command:
$ nano .env
Then, change the DATABASE_URL to match your locally running PostgreSQL database. Here’s how it should look:
DATABASE_URL=”postgresql://sammy:your_password@localhost:5432/my-blog?schema=public”
Make sure to replace sammy and your_password with the actual username and password you set in the Docker Compose file. Once you’re done, save and close the .env file.
Congrats! You’ve now successfully set up PostgreSQL using Docker, installed the Prisma CLI, and connected Prisma to your PostgreSQL database through the .env file. The next step will be to define your data model in Prisma and create the corresponding database tables.
For more on setting up Prisma with PostgreSQL and using it effectively, check out this comprehensive guide on Connecting Prisma with PostgreSQL.
Step 3 — Defining Your Data Model and Creating Database Tables
In this step, you’ll define your data model in the Prisma schema file. This is where you lay out how you want your database to look. Afterward, we’ll use Prisma Migrate to translate your model into SQL and create the corresponding database tables.
So, since you’re building a blogging application, the two main pieces of data you’ll need are users and posts. Prisma makes it easy to define how these entities should relate to each other with its own data modeling language. This language lets you lay things out in a simple, clear way.
To start, open up the schema.prisma file that was created during the Prisma setup. You can open it by running this:
$ nano prisma/schema.prisma
Now, in this file, we’re going to define two models: User and Post. Each model represents a key part of your app. The fields inside each model correspond to the properties of the user and post, like name, email, content, and so on. Here’s how you’ll define the two models:
model User {
id Int @default(autoincrement()) @id
email String @unique
name String?
posts Post[]
}</p>
<p>model Post {
id Int @default(autoincrement()) @id
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
Here’s a quick rundown of what each model does:
- The User model has an auto-incrementing id, a unique email field, an optional name field, and a list of posts. The posts field links a user to multiple posts—more on that in a sec.
- The Post model has an auto-incrementing id, a title, optional content, a published field (defaulting to false), and an author field that links each post to a user. The authorId field is used to connect the post to a specific user.
The magic here is the relationship: A user can have many posts, but each post can only have one author. This is called a one-to-many relationship, and it’s represented by the posts field in the User model and the author field in the Post model.
Once you’ve added these models to the schema.prisma file, save and exit.
Now, we’re going to create the corresponding database tables based on these models using Prisma Migrate. To do this, you’ll run the following command:
$ npx prisma migrate dev –name init
What this command does is generate a new SQL migration and apply it to the database. The –name init part just names the migration—this helps keep things organized. You’ll see something like this in your terminal output:
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource “db”: PostgreSQL database “my-blog”, schema “public” at “localhost:5432”
PostgreSQL database my-blog created at localhost:5432
The following migration(s) have been created and applied from new schema changes:
migrations/
└─ 20201209084626_init/
└─ migration.sql
Running generate… (Use –skip-generate to skip the generators)
✔ Generated Prisma Client (2.13.0) to ./node_modules/@prisma/client in 75ms
After running the migration, Prisma will create a migration file in the prisma/migrations/ folder. The file will contain all the SQL commands needed to create the tables and set up the relationships. It’ll look something like this:
— CreateTable
CREATE TABLE “User” (
“id” SERIAL,
“email” TEXT NOT NULL,
“name” TEXT,
PRIMARY KEY (“id”)
);</p>
<p>— CreateTable
CREATE TABLE “Post” (
“id” SERIAL,
“title” TEXT NOT NULL,
“content” TEXT,
“published” BOOLEAN NOT NULL DEFAULT false,
“authorId” INTEGER,
PRIMARY KEY (“id”)
);</p>
<p>— CreateIndex
CREATE UNIQUE INDEX “User.email_unique” ON “User”(“email”);</p>
<p>— AddForeignKey
ALTER TABLE “Post”
ADD FOREIGN KEY(“authorId”) REFERENCES “User”(“id”) ON DELETE SET NULL ON UPDATE CASCADE;
This SQL migration creates the User and Post tables, along with a foreign key relationship between the two, so that posts are linked to their authors.
Finally, Prisma also generates the Prisma Client in this step. You’ll use this Prisma Client to interact with your database later on, so it’s all set up and ready for you to start making queries.
At this point, you’ve successfully defined your data model and created the necessary tables in the database. In the next step, you’ll install Prisma Client into your project, so you can query your database easily.
For more on defining data models and creating database tables with Prisma, you can explore this in-depth guide on Prisma Data Modeling and Schema Design.
Step 4 — Exploring Prisma Client Queries in a Plain Script
Prisma Client is like your new best friend when it comes to interacting with your database in Node.js or TypeScript applications. It’s an auto-generated and type-safe query builder that makes it easier to work with databases, replacing older tools like Object-Relational Mappers (ORMs), custom data access layers, or plain SQL queries. You’ll be using Prisma Client to handle all the database operations in your REST API routes.
But before we dive into setting up those routes for your API, let’s first get a feel for how Prisma Client works by writing some basic queries. These queries will help you understand how Prisma connects with your database and how to use it effectively. So, in this step, we’ll write a plain script to experiment with Prisma Client and run some queries.
Installation and Setup
Let’s get started by installing Prisma Client in your project folder. You can do this by running the following command:
$ npm install @prisma/client
Next, create a new folder called src where you’ll store all your source files:
$ mkdir src
Now, inside the src folder, create a TypeScript file named index.ts:
$ nano src/index.ts
This is where you’ll write your script to interact with Prisma Client.
Code Structure
Prisma Client queries always return promises, so you’ll need to use async/await to handle them properly. What this means is that you need to wrap your Prisma Client queries inside an asynchronous function. Below is a basic template that will get you started:
import { PrismaClient } from ‘@prisma/client’</p>
<p>const prisma = new PrismaClient()</p>
<p>async function main() {
// … your Prisma Client queries will go here
}</p>
<p>main()
.catch((e) => console.error(e))
.finally(async () => await prisma.$disconnect())
Explanation of the Boilerplate
Let’s break it down:
- Importing PrismaClient: You bring in PrismaClient from the @prisma/client package you just installed.
- Creating Prisma Client Instance: You create an instance of PrismaClient, which allows you to interact with your database. This instance is named prisma.
- Async Function: The main() function is where your queries will live. Since Prisma queries return promises, you need to mark this function as async.
- Error Handling: If something goes wrong inside the main() function, it will be caught and logged by .catch().
- Closing Database Connection: After your queries are finished, Prisma Client gracefully closes the connection with .finally(async () => await prisma.$disconnect()).
Adding Queries to the Script
Now that you’ve got the boilerplate set up, it’s time to actually start adding some queries. Below is an example of how you can create a new user and also fetch all users from the database:
import { PrismaClient } from ‘@prisma/client’</p>
<p>const prisma = new PrismaClient()</p>
<p>async function main() {
// Create a new user and a related post in one query
const newUser = await prisma.user.create({
data: {
name: ‘Alice’,
email: ‘[email protected]’,
posts: {
create: {
title: ‘Hello World’,
},
},
},
})
console.log(‘Created new user: ‘, newUser)</p>
<p> // Fetch all users with their posts
const allUsers = await prisma.user.findMany({
include: { posts: true },
})
console.log(‘All users: ‘)
console.dir(allUsers, { depth: null })
}</p>
<p>main()
.catch((e) => console.error(e))
.finally(async () => await prisma.$disconnect())
Breakdown of the Queries
Here’s a closer look at what’s happening in these two queries:
- Create Query: prisma.user.create() : This creates a new user in the database. The data object contains the user’s details (name and email). Inside the data object, we also create a post for this user with the title “Hello World”. This is done using Prisma’s nested write query ( posts.create ).
- Find Query: prisma.user.findMany() : This query fetches all user records from the database. The include: { posts: true } option makes sure that for each user, the associated posts are also fetched (because of the relationship between User and Post).
Running the Script
After you’ve added your queries, save and close the file. To run the script, use the following command in your terminal:
$ npx ts-node src/index.ts
Expected Output
Once the script runs successfully, you’ll see output like this in your terminal:
Created new user: { id: 1, email: ‘[email protected]’, name: ‘Alice’ }
[ { id: 1, email: ‘[email protected]’, name: ‘Alice’, posts: [ { id: 1, title: ‘Hello World’, content: null, published: false, authorId: 1 } ] } ]
- Created User: The first part of the output shows the newly created user, including their ID, email, and name.
- Fetched Users: The second part lists all users, including their posts. In this case, Alice has a post titled “Hello World” linked to her.
Validation
If you’re using a database GUI (like pgAdmin for PostgreSQL), you can double-check that the data was added by looking at the User and Post tables. Or, if you want to use Prisma’s own tool, you can launch Prisma Studio by running:
$ npx prisma studio
Now you’ve used Prisma Client to both read and write data to your database. In the next steps, you’ll implement the routes for your REST API to interact with this data programmatically.
To dive deeper into Prisma Client queries and how to use them effectively, check out the comprehensive guide on Using Prisma Client for Data Queries.
Step 5 — Implementing Your First REST API Route
In this step, you’re going to install and set up Express in your app. Express is a really popular web framework for Node.js that will help you build your REST API routes. The first route we’re going to build is a simple GET request that lets you fetch all users from your API. You’ll pull the user data from your PostgreSQL database using Prisma Client, which we already set up in earlier steps.
Installing Express and Dependencies
First thing’s first, let’s install Express into the project with the following command:
$ npm install express
Since we’re working with TypeScript, you also need to install the corresponding TypeScript type definitions for Express. These types help TypeScript understand and check your code for Express. Install these types using this command:
$ npm install @types/express –save-dev
Setting Up Your Express Application
Now that we’ve got the necessary dependencies installed, it’s time to set up Express in your app. Let’s open the main source file, usually index.ts , and start editing. Open it like this:
$ nano src/index.ts
If there’s any code already in this file, feel free to delete it and replace it with the following to kick-start your REST API server:
import { PrismaClient } from ‘@prisma/client’
import express from ‘express’</p>
<p>const prisma = new PrismaClient()
const app = express()</p>
<p>app.use(express.json()) // Middleware to parse JSON bodies
// … your REST API routes will go here</p>
<p>app.listen(3000, () => console.log(‘REST API server ready at: http://localhost:3000’))
Breakdown of the Code
Let’s break down what’s going on here:
- Import PrismaClient and Express: First, we import the necessary modules. We bring in PrismaClient from the Prisma Client library and express from the Express library.
- Creating an Instance of PrismaClient: We create an instance of PrismaClient, called prisma , which we’ll use to interact with the database.
- Creating the Express App: Calling express() gives us an instance of the Express app, stored in the app variable. This is the main thing that handles incoming requests.
- Middleware to Parse JSON: The line app.use(express.json()) tells Express to properly handle JSON data that comes in with requests. This is pretty important since you’ll likely be dealing with JSON in your requests.
- Start the Server: app.listen(3000) starts the server and listens on port 3000. Once it’s running, it’ll log a message to the console, so you know the server is ready to accept requests at http://localhost:3000 .
Implementing the /users Route
Now that your server is set up, it’s time to create the /users route, which will allow you to fetch all users from your database. Add this code between app.use(express.json()) and app.listen() :
app.use(express.json())</p>
<p>app.get(‘/users’, async (req, res) => {
const users = await prisma.user.findMany() // Fetch all users
res.json(users) // Send the list of users as a JSON response
})</p>
<p>app.listen(3000, () => console.log(‘REST API server ready at: http://localhost:3000’))
Here’s what’s going on in the code:
- GET Request for /users: The route handler listens for GET requests at /users . Whenever a request is made to this endpoint, it fetches all users from the database using prisma.user.findMany() .
- Responding with Data: The res.json(users) sends the list of users as a JSON response to the client. This makes it easy for the client to display the data.
Running the Server
After adding the route, save the file and close it. You can start your local web server by running the following command:
$ npx ts-node src/index.ts
Once the server is running, you should see this message in your terminal:
REST API server ready at: http://localhost:3000
Testing the /users Route
To test the /users route, open a new terminal window (make sure the server is still running), and use curl , a terminal-based HTTP client, to send a request to the server:
$ curl http://localhost:3000/users
You should get a response that contains the user data you created earlier. For example, it might look something like this:
[{“id”:1,”email”:”[email protected]”,”name”:”Alice”}]
This response shows the user with ID 1, email [email protected] , and name Alice. Notice that the posts array isn’t included here because we didn’t pass the include option to the findMany query in the /users route.
Testing with GUI Tools
If you’re not into using the terminal and prefer something more visual, you can use GUI-based tools like Hoppscotch or Postman. These tools let you send HTTP requests and view the responses in a way that’s a bit friendlier than the command line.
Next Steps
Now that the /users route is up and running, you’ve got a basic API that can fetch user data. The next steps involve building out more functionality for your REST API, like adding routes to manage posts, update user data, and handle other CRUD operations.
To learn more about creating and implementing REST API routes effectively, explore this detailed resource on Implementing REST APIs in Node.js with Express.
Step 6 — Implementing the Remaining REST API Routes
In this step, you’ll be adding the rest of your REST API routes for your blogging app. By the end of it, your server will be ready to handle a variety of HTTP requests, like GET, POST, PUT, and DELETE. Here’s a rundown of the routes we’ll be adding:
- GET /feed : Fetches all published posts.
- GET /post/:id : Fetches a specific post by its ID.
- POST /user : Creates a new user.
- POST /post : Creates a new post (as a draft).
- PUT /post/publish/:id : Sets the “published” field of a post to true.
- DELETE /post/:id : Deletes a post by its ID.
Implementing the GET Routes
Let’s start by implementing the two GET routes. To get going, stop the server by pressing CTRL+C in your terminal. Then, open up your index.ts file for editing:
nano src/index.ts
Now, let’s add the following lines to define those two GET routes:
app.use(express.json())
app.get(‘/feed’, async (req, res) => {
const posts = await prisma.post.findMany({
where: { published: true }, // Fetch only published posts
include: { author: true }, // Include related author information
})
res.json(posts) // Send the list of published posts
})</p>
<p>app.get(‘/post/:id’, async (req, res) => {
const { id } = req.params
const post = await prisma.post.findUnique({
where: { id: Number(id) }, // Find a specific post by ID
})
res.json(post) // Send the found post
})</p>
<p>app.listen(3000, () => console.log(‘REST API server ready at: http://localhost:3000’))
Breakdown of the GET Routes
- /feed : This route retrieves all the posts that have been published. It uses Prisma Client’s findMany() method with a where condition to get only the posts where the published field is set to true. The include option is also used to get the related author information for each post.
- /post/:id : This route lets you fetch a specific post based on the ID you pass in the URL. It uses Prisma Client’s findUnique() method, and grabs the ID from the URL’s params. That allows the app to return a single post, based on the ID provided.
Testing the GET Routes
Once you’ve added the new routes, save and exit the file. Restart the server with:
npx ts-node src/index.ts
You should see this in the terminal:
REST API server ready at: http://localhost:3000
Testing the /feed Route
To test the /feed route, open a new terminal window (keeping your server running) and use curl to make a request to this endpoint:
curl http://localhost:3000/feed
Since no posts have been published yet, you’ll get an empty array:
[]
Testing the /post/:id Route
Next, let’s test the /post/:id route by making a request for a specific post ID:
curl http://localhost:3000/post/1
If there’s a post with ID 1, you should see something like this:
{
“id”: 1,
“title”: “Hello World”,
“content”: null,
“published”: false,
“authorId”: 1
}
Implementing the POST Routes
Now, we’re moving on to the POST routes for creating new users and posts. Again, stop the server by pressing CTRL+C and open up index.ts for editing:
nano src/index.ts
Add this code to implement the two POST routes:
app.post(‘/user’, async (req, res) => {
const result = await prisma.user.create({
data: { …req.body }, // Pass the request body data to the Prisma create method
})
res.json(result) // Send the created user data
})</p>
<p>app.post(‘/post’, async (req, res) => {
const { title, content, authorEmail } = req.body
const result = await prisma.post.create({
data: {
title,
content,
published: false, // Default value for new posts is false
author: { connect: { email: authorEmail } }, // Link the post to an existing user by email
},
})
res.json(result) // Send the created post data
})</p>
<p>app.listen(3000, () => console.log(‘REST API server ready at: http://localhost:3000’))
Explanation of the POST Routes
- /user : This route allows you to create a new user in the database. It uses Prisma Client’s create() method and passes the data from the request body (like name and email) directly into the query.
- /post : This route creates a new post. The request body should include the post’s title, content, and author’s email. The create() method is used, and the post’s author is linked to an existing user by email using the connect method.
Testing the POST Routes
To create a new user through the /user route, you can send a POST request using curl like this:
curl -X POST -H “Content-Type: application/json” -d ‘{“name”:”Bob”, “email”:”[email protected]”}’ http://localhost:3000/user
This will return something like:
{“id”:2,”email”:”[email protected]”,”name”:”Bob”}
To create a new post via the /post route, run this command:
curl -X POST -H “Content-Type: application/json” -d ‘{“title”:”I am Bob”, “authorEmail”:”[email protected]”}’ http://localhost:3000/post
The response will look like:
{“id”:2,”title”:”I am Bob”,”content”:null,”published”:false,”authorId”:2}
Implementing the PUT and DELETE Routes
Stop the server one more time, open index.ts again, and add the following routes for updating and deleting posts:
nano src/index.ts
Add this code:
app.put(‘/post/publish/:id’, async (req, res) => {
const { id } = req.params
const post = await prisma.post.update({
where: { id: Number(id) },
data: { published: true }, // Set the post’s published field to true
})
res.json(post) // Send the updated post
})</p>
<p>app.delete(‘/post/:id’, async (req, res) => {
const { id } = req.params
const post = await prisma.post.delete({
where: { id: Number(id) }, // Delete the post by its ID
})
res.json(post) // Send the deleted post’s data
})</p>
<p>app.listen(3000, () => console.log(‘REST API server ready at: http://localhost:3000’))
Explanation of the PUT and DELETE Routes
- /post/publish/:id (PUT) : This route is used to publish a post by setting its published field to true. It grabs the post’s ID from the URL parameters and uses the update() method to modify the post’s status.
- /post/:id (DELETE) : This route deletes a post by its ID using the delete() method.
Testing the PUT and DELETE Routes
To test the PUT route and publish a post, use this curl command:
curl -X PUT http://localhost:3000/post/publish/2
After publishing the post, you can test the DELETE route with:
curl -X DELETE http://localhost:3000/post/1
To make sure the post with ID 1 was deleted, send another GET request:
curl http://localhost:3000/post/1
Final Result
At this point, you’ve successfully added all the remaining REST API routes for your blogging app. Your API now supports GET, POST, PUT, and DE
For a deeper dive into implementing REST API routes with Node.js and Express, check out this insightful guide on Implementing REST APIs with Node.js and Express.
Conclusion
In conclusion, building a REST API with Prisma, PostgreSQL, TypeScript, and Express equips you with the tools to create efficient and scalable applications. By leveraging Prisma ORM for seamless database management, PostgreSQL for reliable data storage, and TypeScript for type safety, you ensure a robust foundation for your API. With Express, you can easily implement and test routes, managing your users and posts effectively. This tutorial not only walks you through the setup and integration process but also provides essential techniques for handling CRUD operations. As you continue building REST APIs, embracing these tools will help streamline development and improve the maintainability of your projects. Moving forward, we can expect even more powerful integrations and updates in these frameworks, enhancing the developer experience further.
By mastering these technologies, you’ll be well on your way to creating more advanced, full-fledged web applications.