Routes and errors
Read path and query parameters
Use path parameters to identify one resource and query parameters to filter or shape a collection.
8 minute lesson
Path and query parameters solve different problems. /books/42 identifies one book; /books?author=le-guin asks for a filtered collection.
Read path values with c.req.param() and query values with c.req.query(). Both arrive as strings and both are untrusted input. Return 404 when a valid identifier names no resource.
app.get('/books/:id', c => {
const id = c.req.param('id')
const book = books.find(item => item.id === id)
if (!book) return c.json({ type: 'about:blank', title: 'Book not found', status: 404 }, 404)
return c.json({ book })
})
Separate malformed input from an absent resource. If IDs have a required shape, reject a malformed value with 400; return 404 only after a valid ID has been looked up and is missing. A filter that matches no books is different again: it returns 200 with an empty collection.
Define normalization explicitly. Decide whether author matching is exact or case-insensitive, whether surrounding whitespace is meaningful, and what repeated or empty query parameters do. Do not copy a query value into SQL or a response header before validation. Test encoded characters, an empty author, a malformed ID, and a valid missing ID so routing, decoding, validation, and lookup failures remain distinguishable.
Add the detail route and an optional author filter to the collection route.
Lesson completed