Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,149 @@
---
title: "REST"
metaTitle: ""
metaDescription: ""
title: 'REST'
metaTitle: ''
metaDescription: ''
---

Coming 🔜
## Overview

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

![](https://imgur.com/dbRvgHc.png)

## 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 are a few examples:

- [Express](https://expressjs.com/)
- [koa](https://koajs.com/)
- [hapi](https://hapi.dev/)
- [Fastify](https://www.fastify.io/)
- [Sails](https://sailsjs.com/)
- [AdonisJs](https://adonisjs.com/)
- [NestJS](https://nestjs.com/)
- [Next.js](https://nextjs.org/)
- [Foal TS](https://foalts.org/)
- [Polka](https://github.com/lukeed/polka)
- [Micro](https://github.com/zeit/micro)
- [Feathers](https://feathersjs.com/)

## Examples

### REST API server example

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

```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?
}

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

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](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express).

#### `GET`

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

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:

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

#### `POST`

```ts
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`

```ts
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`

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

### Ready-to-tun example projects

You can find several ready-to-tun examples that show how to implement a REST API with Prisma Client in the [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository.

| Example | Language | Stack | Description |
| :----------------------------------------------------------------------------------------------- | :--------- | ------------ | ----------------------------------------------------------------- |
| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-nextjs) | TypeScript | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API |
| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express) | TypeScript | Backend only | Simple REST API with Express |
| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-nextjs) | JavaScript | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API |
| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-express) | JavaScript | Backend only | Simple REST API with Express |
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,8 @@ The _data source connector_ determines what _native database type_ each of these

Expand below to see the mappings per connector and generator.

<!--
<Details><Summary>Scalar mapping to connectors and generators</Summary>
s
<details><summary>Scalar mapping to connectors and generators</summary>
<br />

**Connectors**
Expand All @@ -135,7 +135,7 @@ Expand below to see the mappings per connector and generator.
| `Float` | `number` |
| `DateTime` | `Date` |

</Details> -->
</details>

## Enums

Expand All @@ -149,7 +149,6 @@ Enums are considered [scalar](#scalar-types) types in the Prisma data model. The

Enums are defined via the `enum` block.


## Naming enums

Enum names must start with a letter. They are are typically spelled in [PascalCase](http://wiki.c2.com/?PascalCase) and use the singular form (e.g. `Role` instead of `role`, `roles` or `Roles`).
Expand Down Expand Up @@ -201,17 +200,18 @@ Attributes modify the behavior of a [field](#fields) or block (e.g. [models](#mo

Here's a quick overview of the available field attributes:

| Name | Database representation | Arguments | Description |
| :---------- | :--------------------------- | :---------------------------------------- | :------------------------------------------------------------------------------------- |
| `@id` | `PRIMARY KEY` | - | Defines a single-field ID on the model. |
| `@@id` | `PRIMARY KEY` | A list of field references | Defines a multi-field ID on the model. |
| `@default` | `DEFAULT` | An expression (e.g. `5`, `true`, `now()`) | Defines a default value for this field. `@default` takes an expression as an argument. |
| `@unique` | `UNIQUE` | - | Defines a unique constraint for this field. |
| `@@unique` | `UNIQUE` | A list of field references | Defines a unique constraint for the specified fields. |
| `@@index` | `INDEX` | A list of field references | Defines an index. |
| `@relation` | `FOREIGN KEY` / `REFERENCES` | A name and/or a list of field references | Defines meta information about the relation. [Learn more](). |
| `@map` | n/a | The name of the target database column | Maps a field name from the Prisma schema to a different column name. |
| `@@map` | n/a | The name of the target database table | Maps a model name from the Prisma schema to a differenttable name. |
| Name | Database representation | Arguments | Description |
| :----------- | :--------------------------- | :---------------------------------------- | :------------------------------------------------------------------------------------- |
| `@id` | `PRIMARY KEY` | - | Defines a single-field ID on the model. |
| `@@id` | `PRIMARY KEY` | A list of field references | Defines a multi-field ID on the model. |
| `@default` | `DEFAULT` | An expression (e.g. `5`, `true`, `now()`) | Defines a default value for this field. `@default` takes an expression as an argument. |
| `@unique` | `UNIQUE` | - | Defines a unique constraint for this field. |
| `@@unique` | `UNIQUE` | A list of field references | Defines a unique constraint for the specified fields. |
| `@@index` | `INDEX` | A list of field references | Defines an index. |
| `@relation` | `FOREIGN KEY` / `REFERENCES` | A name and/or a list of field references | Defines meta information about the relation. [Learn more](). |
| `@map` | n/a | The name of the target database column | Maps a field name from the Prisma schema to a different column name. |
| `@@map` | n/a | The name of the target database table | Maps a model name from the Prisma schema to a differenttable name. |
| `@updatedAt` | n/a | - | Automatically stores the time when a record was last updated. |

Here's an overview of the extact signatures of all attributes:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ export type UserWhereUniqueInput = {
};
```

<!--
<details><summary>Expand for a multi-field ID/unique example</summary>

In case your model has a multi-field ID or unique attribute such as the following:
Expand All @@ -113,7 +112,7 @@ export type FirstNameLastNameCompoundUniqueInput = {
}
```

</details> -->
</details>

#### Reference

Expand Down Expand Up @@ -568,7 +567,6 @@ export type UserWhereUniqueInput = {
};
```

<!--
<details><summary>Expand for a multi-field ID/unique example</summary>

In case your model has a multi-field ID or unique attribute such as the following:
Expand Down Expand Up @@ -596,7 +594,7 @@ export type FirstNameLastNameCompoundUniqueInput = {
```

</details>
-->


#### Reference

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ export type QueryEvent = {

Note that `query` contains the SQL query and `params` contains any query parameters for the SQL query.

<!--
<details><summary>Expand to see a logging example</summary>

With the above configuration, assume you're sending the following query with Prisma Client:
Expand Down Expand Up @@ -177,7 +176,7 @@ This API call generates two SQL queries that are being sent as events to the cal
}
```

</details> -->
</details>

#### Logging `info` events

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ metaDescription: ""

Prisma Client provides features that are typically not achievable with relational databases. These features are referred to as _polyfills_.

- Initializing [ID]() values with `cuid` and `uuid` values (requires [Prisma Migrate]())
- Initializing [ID]() values with `cuid` and `uuid` values
- Using [`@updatedAt`]() to store the time when a record was last updated
- [Making 1-1-relations required on both sides]()
- [Implicit many-to-many relations]()
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ Note that as you evolve the application, this process can be repeated for an ind

![](https://imgur.com/8Tp9jRL.png)


## Rules and conventions

Prisma employs a number of conventions for translating a database schema into a Prisma data model:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,18 +154,18 @@ The `generate` command recognizes the following options to modify its behavior:
prisma2 generate
```

✔ Generated Prisma Client to ./node_modules/@prisma/client in 61ms
✔ Generated Prisma Client to ./node_modules/@prisma/client in 61ms

You can now start using Prisma Client in your code:
You can now start using Prisma Client in your code:

```
import { PrismaClient } from '@prisma/client'
// or const { PrismaClient } = require('@prisma/client')
```
import { PrismaClient } from '@prisma/client'
// or const { PrismaClient } = require('@prisma/client')

const prisma = new PrismaClient()
```
const prisma = new PrismaClient()
```

Explore the full API: http://pris.ly/d/client
Explore the full API: http://pris.ly/d/client

**Generate Prisma Client using a non-default `schema.prisma` path**

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ Congratulations, you just created a table called `User` in the database. The tab
CREATE UNIQUE INDEX "User_email_key" ON "User"(email text_ops);
```

<!--
<details><summary>Alternative: Define the constraint as a <strong>table constraint</strong></summary>
<br />

Expand All @@ -84,7 +83,7 @@ CREATE TABLE "public"."User" (
);
```

</details> -->
</details>

## 3. Create a table with a multi-column unique constraint and index

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ Congratulations, you just created a table called `User` in the database. The tab
CREATE UNIQUE INDEX `email` ON `UniqueDemo`.`User`(`email`);
```

<!--
<details><summary>Alternative: Define the constraint as a <strong>table constraint</strong></summary>
<br />

Expand All @@ -96,7 +95,7 @@ CREATE TABLE `UniqueDemo`.`User` (
);
```

</details> -->
</details>

## 3. Create a table with a multi-column unique constraint and index

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ Congratulations, you just created a table called `User` in the database. The tab
CREATE UNIQUE INDEX "sqlite_autoindex_User_1" ON "User"("email");
```

<!--
<details><summary>Alternative: Define the constraint as a <strong>table constraint</strong></summary>
<br />

Expand All @@ -84,7 +83,7 @@ CREATE TABLE "User" (
);
```

</details> -->
</details>

## 3. Create a table with a multi-column unique constraint and index

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ psql ForeignKeyDemo < single-column-foreign-key.sql

Congratulations, you just created two tables called `User` and `Post` in the database. The `Post` table references the `User` table via the foreign key defined on the `author` column.

<!--

<details><summary>Alternative: Define the constraint as a <strong>column constraint</strong></summary>
<br />

Expand All @@ -86,7 +86,7 @@ CREATE TABLE "public"."Post" (
);
```

</details> -->
</details>

## 3. Create a table with a multi-column foreign key constraint

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ sqlite3 ForeignKeyDemo.db < single-column-foreign-key.sql

Congratulations, you just created two tables called `User` and `Post` in the database. The `Post` table references the `User` table via the foreign key defined on the `author` column.

<!--
<details><summary>Alternative: Define the constraint as a <strong>column constraint</strong></summary>
<br />

Expand All @@ -84,7 +83,7 @@ CREATE TABLE "Post" (
);
```

</details> -->
</details>

## 3. Create a table with a multi-column foreign key constraint

Expand Down
Loading