DEV Community

Omar Dulaimi
Omar Dulaimi

Posted on

How to create a JSON server from your Prisma schema?

The library called json-server allows you to quickly run a REST API server from just a small JSON file. Which can be really useful when your building something new or trying out a frontend project.

You can make this JSON file by hand of course. But it would get tedious when your schema grows with time.

So, how can we automate the generation of this JSON file?

Here's what you need to do:

1- Install the generator

  • Using npm
 npm install prisma-json-server-generator
Enter fullscreen mode Exit fullscreen mode
  • Using yarn:
 yarn add prisma-json-server-generator
Enter fullscreen mode Exit fullscreen mode

2- Add the generator to your Prisma schema

generator json_server {
  provider       = "prisma-json-server-generator"
  outputFileName = "db.json"
}
Enter fullscreen mode Exit fullscreen mode

3- Run npx prisma generate for your schema(or the example below)

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

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?
}
Enter fullscreen mode Exit fullscreen mode

Will generate the db.json file.

4- Install json-server

npm install -g json-server
Enter fullscreen mode Exit fullscreen mode

5- Now run your server!

json-server db.json
Enter fullscreen mode Exit fullscreen mode

You will see something like this:

json server running

Top comments (0)