Get Started

Build an App

Goals

On this page, you will learn how to:

  • Configure a Node app with TypeScript
  • Implement a REST API using Express.js & Prisma client
  • Test your REST API using curl

Configure project

You'll use Express.js as your web server. Add the typescript, ts-node, express and body-parser dependencies to your project with this command:

npm install --save typescript ts-node express body-parser
Copy

Define and implement API

There will be six routes that provide the API for a simple blogging application:

  • GET

    • /posts/published: Returns all published posts
    • /post/:postId: Returns a specific post by its id
    • /posts/user/:userId: Returns all the post written by a specific user
  • POST

    • /user: Create a new user
    • /post/draft: Create a new unpublished post
  • PUT

    • /post/publish: Publish a post

Replace the current contents of index.ts with the following code:

import { prisma } from './generated/prisma-client'
import * as express from 'express'
import * as bodyParser from 'body-parser'

const app = express()

app.use(bodyParser.json())

app.get(`/posts/published`, async (req, res) => {
  const publishedPosts = await prisma.posts({ where: { published: true } })
  res.json(publishedPosts)
})

app.get('/post/:postId', async (req, res) => {
  const { postId } = req.params
  const post = await prisma.post({ id: postId })
  res.json(post)
})

app.get('/posts/user/:userId', async (req, res) => {
  const { userId } = req.params
  const postsByUser = await prisma.user({ id: userId }).posts()
  res.json(postsByUser)
})

app.post('/user', async (req, res) => {
  const newUser = await prisma.createUser(req.body)
  res.json(newUser)
})

app.post('/post/draft', async (req, res) => {
  const newPost = await prisma.createPost(req.body)
  res.json(newPost)
})

app.put(`/post/publish/:postId`, async (req, res) => {
  const { postId } = req.params
  const updatedPost = await prisma.updatePost({
    where: { id: postId },
    data: { published: true },
  })
  res.json(updatedPost)
})

app.listen(3000, () =>
  console.log('Server is running on http://localhost:3000'),
)
Copy

Start the server

Start the server with this command:

npm run start
Copy

You can now use a tool like curl or Postman to explore your the functionlity of the routes.

Testing the REST API using curl

Create new draft
Publish a draft
Fetch post by ID
Create user
curl -X POST \
  http://localhost:3000/post/draft \
  -H 'Content-Type: application/json' \
  -d '{
  "title": "Awesome Post"
}'
Copy

In some snippets, you need to replace the __USER__ID__ or __POST_ID__ placeholder with the ID of an actual user.

Congratulations! 🚀 You made it through the quickstart tutorial and learned how to use Prisma and the Prisma client to build a REST API.
Next Step