Building a REST API with Node.js and Express
Routes, middleware, validation, status codes, and error handling for a JSON API, tested with curl.
Model Resources Before Writing Routes
A REST-style API exposes resources through URLs and uses HTTP methods to describe operations. For the study planner, a plan is a resource and study sessions belong to a plan. The browser sends JSON; the server checks the request, applies business rules, and returns JSON with an HTTP status that explains the result.
Keep endpoints predictable. Use plural nouns for collections, path parameters for a specific resource, and query parameters for filtering or pagination. The server—not the route name—must enforce identity and ownership. In this lesson the API accepts a student ID as a teaching placeholder; the authentication lesson replaces that untrusted input with the verified session identity.
| Request | Meaning | Typical result |
|---|---|---|
| GET /api/plans | List the caller’s plans | 200 with a plans array |
| GET /api/plans/:id | Read one authorized plan | 200 or 404 |
| POST /api/plans | Create a plan from validated JSON | 201 with the new plan |
| PATCH /api/plans/:id | Change selected plan fields | 200 with updated data |
| DELETE /api/plans/:id | Remove an authorized plan | 204 with no body |
Create an Express App with Middleware
Express is a Node.js web framework built around middleware and routes. Middleware receives a request, response, and a function that continues the chain. JSON parsing is middleware, as are request logging, authentication, and error handling. Register middleware in a deliberate order: parsers and common middleware first, routes next, and the error handler last.
import express from "express"
import { plansRouter } from "./routes/plans.js"
import { errorHandler } from "./middleware/error-handler.js"
const app = express()
app.use(express.json({ limit: "32kb" }))
app.get("/health", (_request, response) => {
response.status(200).json({ status: "ok" })
})
app.use("/api/plans", plansRouter)
app.use(errorHandler)
export { app }The parser limit is a defensive boundary against unexpectedly large JSON bodies; choose an appropriate limit for the application. A production entry point should also configure a trusted proxy only when the hosting platform requires it, and should not trust arbitrary forwarded headers.
Keep Route Handlers Focused
A route should parse the request, validate its input, call an application function, and translate its result into an HTTP response. Business logic and database access are easier to test when they are not buried in a long callback. Avoid sending internal exception messages to clients because they may reveal implementation details.
import { Router } from "express"
import { z } from "zod"
import { asyncHandler } from "../utils/async-handler.js"
import { createPlan, listPlans } from "../services/plans.js"
const router = Router()
const createPlanSchema = z.object({
title: z.string().trim().min(2).max(100),
examDate: z.string().date().optional(),
})
router.get("/", asyncHandler(async (_request, response) => {
const plans = await listPlans()
response.status(200).json({ plans })
}))
router.post("/", asyncHandler(async (request, response) => {
const input = createPlanSchema.parse(request.body)
const plan = await createPlan(input)
response.status(201).json({ plan })
}))
export { router as plansRouter }The schema defines the external input contract and trims a title before it enters application code. Parsing can throw a Zod validation error; the shared error handler will map it to a client response. In the actual app, the service should receive an authenticated user ID and ensure created plans belong to that user.
Treat Every Request as Untrusted
Browsers, scripts, and other services can send malformed input regardless of what your form permits. Validate body, path, and query values at the server boundary. Check required fields, length, format, and allowed enum values; then validate domain rules, such as whether an exam date is sensible for the learner. A schema library gives one explicit definition that can be reused by route tests.
import { z } from "zod"
export const createSessionSchema = z.object({
title: z.string().trim().min(2).max(120),
subject: z.string().trim().min(1).max(60),
plannedMinutes: z.number().int().min(5).max(240),
scheduledFor: z.string().datetime().optional(),
})
export type CreateSessionInput = z.infer<typeof createSessionSchema>
export function parseCreateSession(body: unknown): CreateSessionInput {
return createSessionSchema.parse(body)
}Notice the input type is inferred from the same runtime schema. TypeScript types disappear at runtime, so declaring a body type alone does not validate JSON received over HTTP. Limit request size, avoid accepting fields that can set roles or ownership, and map validation errors to a clear but non-sensitive response.
studentId or role must not become writable merely because the client supplied it.Centralise Errors in One Middleware
Without a shared error path, one route returns a string, another leaks a stack trace, and a third forgets to end the response. Define an application error with an HTTP status and a safe message, then use error middleware to map known errors and log unknown ones. In Express, error-handling middleware has four parameters and should be registered after the routes.
import type { ErrorRequestHandler } from "express"
import { ZodError } from "zod"
export class HttpError extends Error {
constructor(public status: number, message: string) {
super(message)
this.name = "HttpError"
}
}
export const errorHandler: ErrorRequestHandler = (error, _request, response, _next) => {
if (error instanceof ZodError) {
response.status(400).json({ error: "Invalid request", issues: error.issues })
return
}
if (error instanceof HttpError) {
response.status(error.status).json({ error: error.message })
return
}
console.error("Unhandled API error", error)
response.status(500).json({ error: "Something went wrong" })
}For asynchronous route handlers, make sure rejected promises are forwarded to Express's error pipeline. A small wrapper is one option; a router-specific async mechanism is another. Confirm the behavior for the Express version and typings in your project rather than assuming thrown asynchronous errors are automatically handled in every setup.
import type { Request, Response, NextFunction, RequestHandler } from "express"
type AsyncRoute = (request: Request, response: Response, next: NextFunction) => Promise<unknown>
export function asyncHandler(handler: AsyncRoute): RequestHandler {
return (request, response, next) => {
Promise.resolve(handler(request, response, next)).catch(next)
}
}Exercise the API from the Client's Point of View
Test routes through HTTP, not only by calling helper functions. A request tool such as curl helps verify the URL, headers, body, status, and response together. Keep examples local and use test data; never paste real credentials or a student's private information into shared terminal history.
curl -i http://localhost:3000/health
curl -i -X POST http://localhost:3000/api/plans \
-H "Content-Type: application/json" \
-d '{"title":"Midterm revision"}'
curl -i -X POST http://localhost:3000/api/plans \
-H "Content-Type: application/json" \
-d '{"title":""}'- Check a valid create request returns 201 and a stable JSON shape.
- Send invalid JSON, a missing title, and an overly long title; expect a client error.
- Request a missing plan and verify the intended not-found response.
- Cause a controlled service failure and verify the response is safe while server logs retain context.
- Repeat tests after changing middleware order or schema rules.
Common Mistakes
Trusting the client-side form as validation
Why: Anyone can call the API directly with a different payload.
Fix: Parse and validate every request on the server.
Returning 200 for a failed operation
Why: Clients and monitoring treat the HTTP request as successful.
Fix: Use an appropriate 4xx or 5xx status and a stable error body.
Putting database queries and policy in route callbacks
Why: Handlers become hard to test and reuse.
Fix: Separate validation, service logic, and persistence responsibilities.
Leaking raw exception messages
Why: Errors can reveal SQL, infrastructure, paths, or secrets.
Fix: Map expected errors safely and log unexpected errors on the server.
Create a Validated Planner API
Practice
A small HTTP contract with safe failure behavior
- Implement GET /api/plans and POST /api/plans with a clear JSON response shape.
- Define Zod schemas for creating a plan and a study session, including sensible length limits.
- Add shared error middleware for validation, expected application errors, and unknown failures.
- Write curl requests for success, bad input, missing resources, and a server failure.
- Refactor the POST route so the service receives only validated fields and a trusted user identity seam.
Hint: The authentication and persistence lessons will replace in-memory or placeholder services; keep the API contract independent of storage.
🎯 Key Takeaways
- ✓HTTP methods, URLs, status codes, and response shapes form an API contract.
- ✓Express middleware order determines how requests and errors flow.
- ✓Validate body, path, and query data at runtime with a schema.
- ✓Separate routes from application logic and persistence.
- ✓Centralize expected error mapping and keep unexpected details out of responses.
- ✓Test the API over HTTP with valid and invalid requests.
- Use the official Express and Zod documentation for current setup and API details. Keep exact dependency versions in the repository manifest and lockfile.
Next
What comes next
Replace placeholder service functions with relational tables, migrations, and typed database queries.
Lesson 07 · PostgreSQL with an ORM — Prisma →HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
