Building a REST API with Prisma
Prisma is the most popular TypeScript ORM for good reason: it generates a fully typed client from your schema, handles migrations, and provides an intuitive query API. Here is how to build a complete REST API with Prisma, Express, and TypeScript.
Schema Design
Start with your Prisma schema. Define your models with fields, types, relations, and constraints. Use @id for primary keys, @unique for unique constraints, @default for defaults, and @relation for foreign keys. Run prisma format to auto-format your schema and prisma validate to catch errors before generating.
Generated Client
Run prisma generate to create the typed client. The generated client provides methods for every model: findMany, findUnique, create, update, delete, and upsert. All inputs and outputs are fully typed — if you rename a field in your schema and regenerate, TypeScript catches every usage that needs updating.
Route Structure
Organize routes by resource: /api/users, /api/posts, /api/comments. Each resource file exports a router with handlers for GET (list and detail), POST (create), PUT (update), and DELETE. Use middleware for authentication, validation, and error handling. Parse and validate request bodies with zod schemas that mirror your Prisma types.
Pagination and Filtering
Implement cursor-based pagination for list endpoints. Accept cursor and take query parameters. Use Prisma cursor pagination with orderBy for consistent results. For filtering, map query parameters to Prisma where clauses. Use the contains, startsWith, gte, lte, and in filters for flexible querying.
Error Handling and Validation
Catch Prisma-specific errors (PrismaClientKnownRequestError) and map them to HTTP status codes: P2002 (unique constraint) maps to 409 Conflict, P2025 (record not found) maps to 404 Not Found. Wrap all handlers in a try-catch that returns 500 for unexpected errors with a generic message in production and the full error in development.
Related Posts
Sponsor Our Newsletter
Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.
All sponsored content is clearly labeled per our editorial policy.