This example shows how to implement a REST API with TypeScript using Express and Prisma Client. It is based on a SQLite database, you can find the database file with some dummy data at ./prisma/dev.db
.
Download this example:
curl https://codeload.github.com/prisma/prisma-examples/tar.gz/latest | tar -xz --strip=2 prisma-examples-latest/typescript/rest-express
Install npm dependencies:
cd rest-express
npm install
Alternative: Clone the entire repo
Clone this repository:
git clone [email protected]:prisma/prisma-examples.git --depth=1
Install npm dependencies:
cd prisma-examples/typescript/rest-express
npm install
Run the following command to create your SQLite database file. This also creates the User
and Post
tables that are defined in prisma/schema.prisma
:
npx prisma migrate dev --name init
Now, seed the database with the sample data in prisma/seed.ts
by running the following command:
npx prisma db seed
npm run dev
The server is now running on http://localhost:3000
. You can now the API requests, e.g. http://localhost:3000/feed
.
You can access the REST API of the server using the following endpoints:
/post/:id
: Fetch a single post by itsid
/feed?searchString={searchString}&take={take}&skip={skip}&orderBy={orderBy}
: Fetch all published posts- Query Parameters
searchString
(optional): This filters posts bytitle
orcontent
take
(optional): This specifies how many objects should be returned in the listskip
(optional): This specifies how many of the returned objects in the list should be skippedorderBy
(optional): The sort order for posts in either ascending or descending order. The value can eitherasc
ordesc
- Query Parameters
/user/:id/drafts
: Fetch user's drafts by theirid
/users
: Fetch all users
/post
: Create a new post- Body:
title: String
(required): The title of the postcontent: String
(optional): The content of the postauthorEmail: String
(required): The email of the user that creates the post
- Body:
/signup
: Create a new user- Body:
email: String
(required): The email address of the username: String
(optional): The name of the userpostData: PostCreateInput[]
(optional): The posts of the user
- Body:
/publish/:id
: Toggle the publish value of a post by itsid
/post/:id/views
: Increases theviewCount
of aPost
by oneid
/post/:id
: Delete a post by itsid
Evolving the application typically requires two steps:
- Migrate your database using Prisma Migrate
- Update your application code
For the following example scenario, assume you want to add a "profile" feature to the app where users can create a profile and write a short bio about themselves.
The first step is to add a new table, e.g. called Profile
, to the database. You can do this by adding a new model to your Prisma schema file file and then running a migration afterwards:
// ./prisma/schema.prisma
model User {
id Int @default(autoincrement()) @id
name String?
email String @unique
posts Post[]
+ profile Profile?
}
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String?
published Boolean @default(false)
viewCount Int @default(0)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
+model Profile {
+ id Int @default(autoincrement()) @id
+ bio String?
+ user User @relation(fields: [userId], references: [id])
+ userId Int @unique
+}
Once you've updated your data model, you can execute the changes against your database with the following command:
npx prisma migrate dev --name add-profile
This adds another migration to the prisma/migrations
directory and creates the new Profile
table in the database.
You can now use your PrismaClient
instance to perform operations against the new Profile
table. Those operations can be used to implement API endpoints in the REST API.
Update your index.ts
file by adding a new endpoint to your API:
app.post('/user/:id/profile', async (req, res) => {
const { id } = req.params
const { bio } = req.body
const profile = await prisma.profile.create({
data: {
bio,
user: {
connect: {
id: Number(id)
}
}
}
})
res.json(profile)
})
Restart your application server and test out your new endpoint.
/user/:id/profile
: Create a new profile based on the user id- Body:
bio: String
: The bio of the user
- Body:
Expand to view more sample Prisma Client queries on Profile
Here are some more sample Prisma Client queries on the new Profile
model:
const profile = await prisma.profile.create({
data: {
bio: 'Hello World',
user: {
connect: { email: '[email protected]' },
},
},
})
const user = await prisma.user.create({
data: {
email: '[email protected]',
name: 'John',
profile: {
create: {
bio: 'Hello World',
},
},
},
})
const userWithUpdatedProfile = await prisma.user.update({
where: { email: '[email protected]' },
data: {
profile: {
update: {
bio: 'Hello Friends',
},
},
},
})
If you want to try this example with another database than SQLite, you can adjust the the database connection in prisma/schema.prisma
by reconfiguring the datasource
block.
Learn more about the different connection configurations in the docs.
Expand for an overview of example configurations with different databases
For PostgreSQL, the connection URL has the following structure:
datasource db {
provider = "postgresql"
url = "postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA"
}
Here is an example connection string with a local PostgreSQL database:
datasource db {
provider = "postgresql"
url = "postgresql://janedoe:mypassword@localhost:5432/notesapi?schema=public"
}
For MySQL, the connection URL has the following structure:
datasource db {
provider = "mysql"
url = "mysql://USER:PASSWORD@HOST:PORT/DATABASE"
}
Here is an example connection string with a local MySQL database:
datasource db {
provider = "mysql"
url = "mysql://janedoe:mypassword@localhost:3306/notesapi"
}
Here is an example connection string with a local Microsoft SQL Server database:
datasource db {
provider = "sqlserver"
url = "sqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;"
}
- Check out the Prisma docs
- Share your feedback in the
prisma2
channel on the Prisma Slack - Create issues and ask questions on GitHub
- Watch our biweekly "What's new in Prisma" livestreams on Youtube