Overview

When building REST APIs, Prisma Client can be used inside your route controllers to send databases queries.

Supported libraries

As Prisma Client is "only" responsible for sending queries to your database, it can be combined with any HTTP server library or web framework of your choice.

Here's a non-exhaustive list of libraries and frameworks you can use with Prisma:

REST API server example

Assume you have a Prisma schema that looks similar to this:

1datasource db {
2 provider = "sqlite"
3 url = "file:./dev.db"
4}
5
6generator client {
7 provider = "prisma-client-js"
8}
9
10model Post {
11 id Int @id @default(autoincrement())
12 title String
13 content String?
14 published Boolean @default(false)
15 author User? @relation(fields: [authorId], references: [id])
16 authorId Int?
17}
18
19model User {
20 id Int @id @default(autoincrement())
21 email String @unique
22 name String?
23 posts Post[]
24}

You can now implement route controller (e.g. using Express) that use the generated Prisma Client API to perform a database operation when an incoming HTTP request arrives. This page only shows few sample code snippets, if you want to run these code snippets, you can use the REST API example.

GET

1app.get('/feed', async (req, res) => {
2 const posts = await prisma.post.findMany({
3 where: { published: true },
4 include: { author: true },
5 })
6 res.json(posts)
7})

Note that the feed endpoint in this case returns a nested JSON response of Post objects that include an author object. Here's a sample response:

1[
2 {
3 "id": "21",
4 "title": "Hello World",
5 "content": "null",
6 "published": "true",
7 "authorId": 42,
8 "author": {
9 "id": "42",
10 "name": "Alice",
11 "email": "alice@prisma.io"
12 }
13 }
14]

POST

1app.post(`/post`, async (req, res) => {
2 const { title, content, authorEmail } = req.body
3 const result = await prisma.post.create({
4 data: {
5 title,
6 content,
7 published: false,
8 author: { connect: { email: authorEmail } },
9 },
10 })
11 res.json(result)
12})

PUT

1app.put('/publish/:id', async (req, res) => {
2 const { id } = req.params
3 const post = await prisma.post.update({
4 where: { id: Number(id) },
5 data: { published: true },
6 })
7 res.json(post)
8})

DELETE

1app.delete(`/post/:id`, async (req, res) => {
2 const { id } = req.params
3 const post = await prisma.post.delete({
4 where: {
5 id: Number(id),
6 },
7 })
8 res.json(post)
9})

Ready-to-run example projects

You can find several ready-to-run examples that show how to implement a REST API with Prisma Client in the prisma-examples repository.

ExampleLanguageStackDescription
rest-nextjsTypeScriptFullstackSimple Next.js app (React) with a REST API
rest-expressTypeScriptBackend onlySimple REST API with Express
rest-nextjsJavaScriptFullstackSimple Next.js app (React) with a REST API
rest-expressJavaScriptBackend onlySimple REST API with Express
Edit this page on Github