Exercises
Objectives
By the end of this lesson, you should be able to:
- Build a complete multi-route Express API from scratch
- Combine route parameters, query parameters, and a JSON body in one project
- Return the correct status code for every outcome, success and failure alike
⚠️ A note on verification: every command and output in this lesson was actually run with Express.
Exercise: A Task List API
Build an Express server managing an in-memory list of tasks, starting from this seed data:
let tasks = [
{ id: 1, title: 'Write lesson', done: false },
{ id: 2, title: 'Verify code', done: true }
];
a) List tasks. GET /tasks returns every task as JSON with status 200. Support an optional ?done=true or ?done=false query parameter that filters the list to only matching tasks.
curl "http://localhost:4007/tasks?done=true"
[{"id":2,"title":"Verify code","done":true}]
b) Get one task. GET /tasks/:id returns the matching task with status 200, or { "error": "Task not found" } with status 404 if no task has that ID.
curl -w " [%{http_code}]" http://localhost:4007/tasks/99
{"error":"Task not found"} [404]
c) Create a task. POST /tasks reads title from req.body (remember express.json()), returns the new task with status 201. If title is missing, return { "error": "title is required" } with status 400.
curl -X POST http://localhost:4007/tasks -H "Content-Type: application/json" -d '{"title":"Ship it"}'
{"id":3,"title":"Ship it","done":false}
d) Update a task. PUT /tasks/:id reads an optional title and/or done from req.body, updates only the fields provided, returns the updated task with status 200, or 404 if the ID doesn’t exist.
curl -X PUT http://localhost:4007/tasks/1 -H "Content-Type: application/json" -d '{"done":true}'
{"id":1,"title":"Write lesson","done":true}
e) Delete a task. DELETE /tasks/:id removes the matching task and returns { "deleted": true } with status 200, or 404 if the ID doesn’t exist.
curl -X DELETE http://localhost:4007/tasks/2
{"deleted":true}
f) Serve a static page. Add a public folder with a simple index.html, and serve it with express.static, alongside all the routes above, in the same running server.
g) Test every route above with curl, checking both the status code (-w " [%{http_code}]" or -i) and the response body for each. Include at least one request that should fail (a missing title, a nonexistent id) for each relevant route.
Recap
This module covered building a real Express server: creating the app and registering routes, matching HTTP methods and paths, reading from req and writing to res, capturing route and query parameters, serving static files, and returning JSON with correct status codes, everything needed for a working, testable API.
Next module: rendering real HTML pages from the server, with a view engine.