Crash Courses · PhD
API Design & Documentation
Design clean, consistent APIs and document them with OpenAPI.
10 min read+200 XP on completionCert: REST APIs Crash Course
Tap any word in the text below to start reading from there.
API Design & Documentation
A well-designed API is predictable, consistent, and self-documented. These principles reduce bugs and client integration time.
Response Envelope Pattern
// Consistent response shape
type ApiSuccess<T> = {
data: T
meta?: {
page?: number
total?: number
has_more?: boolean
}
}
type ApiError = {
error: {
code: string // machine-readable: "COURSE_NOT_FOUND"
message: string // human-readable: "The requested course was not found"
details?: unknown // Zod validation errors, etc.
}
}
// All routes return one of these two shapes
function ok<T>(data: T, meta?: ApiSuccess<T>['meta']): NextResponse {
return NextResponse.json({ data, meta })
}
function err(code: string, message: string, status: number): NextResponse {
return NextResponse.json({ error: { code, message } }, { status })
}
// Usage
return ok(course)
return err('COURSE_NOT_FOUND', 'Course not found', 404)Versioning
app/
api/
v1/
courses/
route.ts ← /api/v1/courses
progress/
route.ts
v2/
courses/
route.ts ← /api/v2/courses (breaking changes)OpenAPI with Zod
// Using next-swagger-doc or zod-to-openapi
import { extendZodWithOpenApi } from 'zod-to-openapi'
const CourseSchema = z.object({
id: z.string().openapi({ example: 'cc-js-m01' }),
title: z.string().openapi({ example: 'JavaScript Fundamentals' }),
xp: z.number().openapi({ example: 150 }),
})
// Auto-generates /api/docs OpenAPI specAPI Design Checklist
✅ Nouns in URLs, verbs as HTTP methods
✅ Consistent response envelope { data, meta } / { error }
✅ HTTP status codes used correctly
✅ Pagination on all list endpoints
✅ Versioned (/v1/) if public-facing
✅ All inputs validated (Zod)
✅ Auth on every non-public endpoint
✅ Rate limiting on auth and write endpoints
✅ CORS configured for production domains
✅ Security headers in placeReading progress
0% read
In this module
Versioning
OpenAPI
Error envelope
Hypermedia (HATEOAS)
0%