メインコンテンツにスキップ

REST

REST API を構築する際、Prisma Client はデータベースクエリを送信するためにルートコントローラー内で使用できます。

REST APIs with Prisma Client

サポートされているライブラリ

Prisma Client は「のみ」データベースにクエリを送信する役割を担っているため、任意の HTTP サーバーライブラリまたは Web フレームワークと組み合わせることができます。

Prisma ORM で使用できるライブラリとフレームワークの網羅的ではないリストを以下に示します。

REST API サーバーの例

次のような Prisma スキーマがあると仮定します。

datasource db {
provider = "sqlite"
url = "file:./dev.db"
}

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

model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}

これで、(例えば Express を使用して)HTTP リクエストが到着したときに生成された Prisma Client API を使用してデータベース操作を実行するルートコントローラーを実装できます。このページでは、いくつかのサンプルコードスニペットのみを示します。これらのコードスニペットを実行する場合は、REST API の例を使用できます。

GET

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

この場合の feed エンドポイントは、author オブジェクトを含む Post オブジェクトのネストされた JSON レスポンスを返すことに注意してください。サンプルレスポンスを以下に示します。

[
{
"id": "21",
"title": "Hello World",
"content": "null",
"published": "true",
"authorId": 42,
"author": {
"id": "42",
"name": "Alice",
"email": "alice@prisma.io"
}
}
]

POST

app.post(`/post`, async (req, res) => {
const { title, content, authorEmail } = req.body
const result = await prisma.post.create({
data: {
title,
content,
published: false,
author: { connect: { email: authorEmail } },
},
})
res.json(result)
})

PUT

app.put('/publish/:id', async (req, res) => {
const { id } = req.params
const post = await prisma.post.update({
where: { id: Number(id) },
data: { published: true },
})
res.json(post)
})

DELETE

app.delete(`/post/:id`, async (req, res) => {
const { id } = req.params
const post = await prisma.post.delete({
where: {
id: Number(id),
},
})
res.json(post)
})

すぐに実行できるプロジェクト例

Prisma Client で REST API を実装する方法や、完全なアプリケーションを構築する方法を示す、すぐに実行できる例を prisma-examples リポジトリで見つけることができます。

スタック説明
expressバックエンドのみTypeScript 用 Express を使用した REST API
fastifyバックエンドのみFastify と Prisma Client を使用した REST API。
hapiバックエンドのみhapi と Prisma Client を使用した REST API
nestjsバックエンドのみREST API を備えた Nest.js アプリ (Express)
nextjsフルスタックREST API を備えた Next.js アプリ (React)