Express REST APIs
Use Express to build a resource-oriented API with route parameters, middleware, validation, and one consistent error format.
By the end, you’ll be able to…
- Create an Express app with route parameters and query strings.
- Explain middleware order and use express.json and error middleware correctly.
- Design CRUD routes that return predictable status codes and response shapes.
01Express is a thin routing layer
Express wraps node:http with routing, middleware, and response helpers. Create an app, register routes, and pass it to app.listen. request.params contains path segments such as :id; request.query contains parsed query-string values. Both are strings until you validate and convert them.
Keep route handlers small. Parse and validate input, call a function that owns the data, then shape the response. That separation makes handlers testable and stops HTTP details from leaking into persistence code. A handler that reads a file directly is harder to reuse than one that calls a repository.
02Middleware runs in order
Middleware is a function with request, response, and next. It can inspect or modify the request, end the response, or pass control onward. app.use(express.json()) parses JSON bodies before your routes; a logger can record timing; an authentication check can reject early. Order matters because Express runs the stack from top to bottom.
Error middleware is the exception: it has four parameters and runs only when next(error) is called or a handler throws. Register it after all routes. In Express 5, rejected promises from async handlers are forwarded automatically; in Express 4, wrap them or call next(error) explicitly. Never leave an async rejection unhandled.
03REST resources and CRUD
REST models the API as resources: /api/books is the collection, and /api/books/:id is one member. Use nouns rather than verbs, plural collection names, and HTTP methods for the action. GET reads, POST creates at the collection, PUT replaces a member, PATCH partially updates, and DELETE removes.
Return 200 for a successful read or update, 201 with a Location header for creation, and 204 for a deletion with no body. A missing member is 404; a duplicate unique value is 409; invalid input is 400. Consistent status codes let clients handle outcomes without parsing prose, and consistent bodies let them reuse one parser.
Collections often need pagination or sorting. Accept them as query parameters with defaults and maximums, for example ?limit=20&offset=0, and return metadata alongside data. Never pass a raw query string into a database or file filter without validation; it is user input like any other.
04Validation and one error shape
Validate at the boundary, before data reaches the repository. Check required fields, types, ranges, and lengths, and collect every problem so the client can fix them in one pass. Return a stable error body such as { error: { code, message, details } } for every failure, including 404 and 500.
Centralize error handling so handlers do not repeat response formatting. Throw an HttpError with a status and code, or call next(error). The middleware logs unexpected failures, hides internal details, and preserves the same shape for validation errors. Never send error.stack to a client; it reveals file paths and implementation details.
The handler can also translate framework errors, such as malformed JSON from express.json, into the same envelope. Check for a status already attached to the error before defaulting to 500, and include a request id so logs and client reports can be matched.
The ideas worth keeping.
- Route parameters identify a resource; query strings filter or shape the response.
- Middleware is an ordered stack, with four-parameter error middleware registered last.
- Use resource nouns, correct status codes, boundary validation, and one error shape everywhere.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Filter a collection with a query parameter
Implement GET /api/books?author=Ada so it returns only books whose author matches case-insensitively. Reject an empty or repeated author parameter with a 400 validation error.
Explore a worked solution
app.get("/api/books", async (request, response, next) => { const { author } = request.query; if (author !== undefined && (typeof author !== "string" || author.trim() === "")) { return next(new HttpError(400, "VALIDATION_ERROR", "author must be a non-empty string.")); } const books = await listBooks(); const data = author ? books.filter((book) => book.author.toLowerCase() === author.toLowerCase()) : books; response.json({ data });});Express may parse a repeated query parameter as an array, so the type check matters. Filtering after validation keeps the comparison safe, and returning { data } matches the collection response shape used elsewhere.
Exercise 2: Add the final 404 and error middleware
Register a catch-all 404 handler and a four-parameter error handler. The 404 returns NOT_FOUND; the error handler uses error.status or 500, logs only server errors, and hides the message for a 500.
Explore a worked solution
app.use((request, response) => { response.status(404).json({ error: { code: "NOT_FOUND", message: "Route not found." }, });});app.use((error, request, response, next) => { if (response.headersSent) return next(error); const status = error.status ?? 500; if (status === 500) console.error(error); response.status(status).json({ error: { code: error.code ?? "INTERNAL_ERROR", message: status === 500 ? "Unexpected server error." : error.message, }, });});The catch-all runs after every route, so only unmatched requests reach it. The error handler must keep four parameters for Express to recognize it, and checking headersSent avoids writing a second response after a streaming failure.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Filter a collection with a query parameter
Implement GET /api/books?author=Ada so it returns only books whose author matches case-insensitively. Reject an empty or repeated author parameter with a 400 validation error.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.