Tutorial 1: Routing, Middleware, and API Boundaries
Unit 4 · Server-side web systems
Objectives
Separate routing, validation, application logic, and persistence.
Design predictable JSON API responses.
Reject invalid input at a trust boundary.
GET /api/courses/466
200 OK
Content-Type: application/json
{"code":"COMP466","title":"Advanced Technologies for Web-Based Systems"}
A route maps a method and path to a handler. Middleware can authenticate, parse input, log requests, and apply common policy before the handler runs. The handler should coordinate a use case rather than contain every database and formatting detail.
Exercises
Define routes for listing, reading, and creating courses.
Validate a JSON body and return a useful 400 response.
Identify which concerns belong in middleware.
Self-check
Why validate at the server boundary?
What is middleware?
When should an API return 404?
Self-Check Quiz
1. What does routing decide?
AnswerRouting selects the handler for an HTTP method and URL path.
2. Should client validation replace server validation?
AnswerNo. Client validation improves feedback, but the server must validate all untrusted input.
Homework
Design a course API with resources, methods, status codes, and error shape.
Implement a handler that validates required fields.
Write one integration test for valid and invalid requests.
Sample answerA good API uses consistent JSON errors such as {"error":"title is required"}, returns 201 for a successful creation, 400 for malformed input, and 404 for a missing course. Validation runs before persistence and the handler delegates database work.