Building a Simple CRUD API with Prisma + Next.js
TL;DR
Using Prisma as an ORM to build a simple CRUD application together with Next.js.
Setting Up Next.js
First things first, let's set up Next.js.
Setting Up Prisma
Installing Prisma
A .env file is created with a DATABASE_URL configured. This time we'll use sqlite3.
.env
Let's write the schema. For now, having a title and content should suffice.
prisma/schema.prisma
Now that we're ready, start the database and run the migration to set up the Prisma client.
Running migrate automatically creates @prisma/client under node_modules. You can also explicitly generate it with npx prisma generate.
Let's verify the table was created.
>For Postgres
Since I might deploy to Heroku or something, I'll also document the Postgres case. First, prepare Postgres with Docker. Since I frequently use Postgres Docker, I use port 15432.
Set the DATABASE_URL in .env as follows. Note that the port has been changed and a password and username are configured.
.env
Prisma Client Configuration
Create the Prisma client configuration under libs. I added query to the log since I want to see what queries are being sent.
Creating the CRUD API
Since this is just a simple verification, I'm not checking the HTTP methods. Also, while it would be better to receive the ID via path parameters in practice, it was a bit cumbersome to do in Next.js, so everything is received in the request body.
Create
First, let's create create-todo to create a Todo.
pages/api/create-todo.ts
Start with yarn dev and send a POST to the API.
READ
Create an endpoint to retrieve the TODO list.
pages/api/get-todos.ts
Send a GET request. We can confirm it was created correctly.
UPDATE
Create an API for updating.
pages/api/update-todo.ts
Check with curl.
The content and updatedAt have indeed been updated.
Delete
Finally, let's implement the Delete part.
pages/api/delete-todo.ts
Let's verify the delete works.