Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: A Blog API

Build a small blog REST API with users, posts and tags, a repository layer shaped like Prisma Client, cursor pagination and proper errors, with the real Prisma schema and a runnable Node stand-in.

In this project you design and build the backend of a blog: authors, posts, tags and comments, exposed as a REST API. You will put the earlier lessons to work: schema design, relations, indexes, cursor pagination, transactions and clean error handling.

Prisma itself cannot run in the browser or on this site's runner, so the project has two parts. The real Prisma code (schema and handlers) is read-only. The runnable part is a labelled stand-in: a small repository written with node:sqlite and node:http whose method names and shapes mirror Prisma Client, so you can run and call the API right here.

Step 1: the schema

PRISMA
generator client {
  provider = "prisma-client"
  output   = "../src/generated"
}

datasource db {
  provider = "postgresql"
}

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

model Post {
  id          Int       @id @default(autoincrement())
  slug        String    @unique
  title       String
  body        String
  published   Boolean   @default(false)
  createdAt   DateTime  @default(now())
  authorId    Int
  author      User      @relation(fields: [authorId], references: [id])
  tags        Tag[]
  comments    Comment[]

  @@index([authorId])
  @@index([published, id])
}

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

model Comment {
  id       Int    @id @default(autoincrement())
  body     String
  postId   Int
  post     Post   @relation(fields: [postId], references: [id], onDelete: Cascade)
  authorId Int
  author   User   @relation(fields: [authorId], references: [id])

  @@index([postId])
}

Notes on the design: Post and Tag form an implicit many-to-many (Prisma creates the join table), comments cascade-delete with their post, and the composite @@index([published, id]) serves "published posts, paged by id".

Step 2: the endpoints

Method and path Purpose
POST /posts create a post with tags (nested write)
GET /posts?cursor=&limit= published posts, cursor-paginated, with author and tags
GET /posts/:slug one post with comments
POST /posts/:slug/comments add a comment

The core handler with real Prisma:

TypeScript
app.get('/posts', async (req, res) => {
  const limit = Math.min(Number(req.query.limit) || 10, 50);
  const cursor = req.query.cursor ? Number(req.query.cursor) : undefined;

  const rows = await prisma.post.findMany({
    where: { published: true },
    orderBy: { id: 'desc' },
    take: limit + 1,
    ...(cursor && { cursor: { id: cursor }, skip: 1 }),
    select: {
      id: true, slug: true, title: true,
      author: { select: { name: true } },
      tags: { select: { name: true } },
    },
  });
  const hasMore = rows.length > limit;
  const items = hasMore ? rows.slice(0, limit) : rows;
  res.json({ items, nextCursor: hasMore ? items.at(-1)!.id : null });
});

app.post('/posts', async (req, res) => {
  try {
    const post = await prisma.post.create({
      data: {
        slug: req.body.slug, title: req.body.title, body: req.body.body, published: true,
        author: { connect: { id: req.body.authorId } },
        tags: { connectOrCreate: req.body.tags.map((name: string) => ({ where: { name }, create: { name } })) },
      },
    });
    res.status(201).json(post);
  } catch (e: any) {
    if (e.code === 'P2002') return res.status(409).json({ error: 'slug already exists' });
    if (e.code === 'P2025') return res.status(404).json({ error: 'author not found' });
    throw e;
  }
});

connectOrCreate reuses an existing tag or makes it, all inside the same implicit transaction. Prisma error codes map to HTTP statuses: P2002 unique violation becomes 409, P2025 record not found becomes 404, P2003 foreign key failure becomes 400 or 409.

Step 3: run a stand-in

This API stores data in SQLite and talks to itself with fetch. The db object has the same call style as Prisma (createPost, listPosts) but is hand-written.

Node.js Stand-in: blog API on node:http + node:sqlite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Step 4: extend it

  1. Add GET /posts/:slug that includes comments with include: { comments: { orderBy: { id: 'asc' }, take: 50 } } and an author select.
  2. Add a deletedAt field and a client extension for soft delete.
  3. Add GET /tags returning each tag with _count: { select: { posts: true } }.
  4. Write integration tests with the rollback pattern from testing Prisma code.
  5. Add an index and check with EXPLAIN that GET /posts uses it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Prisma error code means a unique constraint failed, suited to an HTTP 409?

    P2002 is a unique constraint violation; P2025 is record not found.
  2. 2. What does connectOrCreate on tags do?

    It combines connect and create so tags are shared between posts without manual lookups.
  3. 3. Why fetch limit + 1 posts in the list endpoint?

    An extra row tells you there is more, with no separate count query.
  4. 4. Why cascade-delete comments with onDelete: Cascade?

    A cascade prevents orphan comments and keeps referential integrity.

Summary

  • Model users, posts, tags and comments with relations, an implicit many-to-many and targeted indexes.
  • Use nested writes (connect, connectOrCreate) for atomic creation.
  • Paginate with a cursor and limit + 1; cap the page size.
  • Map Prisma error codes to HTTP statuses.
  • The runnable server here is a node:sqlite stand-in; the Prisma code is read-only.

Next: Project: Inventory and Orders with Transactions