Routing
Structure an API so it stays readable beyond thirty routes.
Routing
An API that returns 200 OK with a body of { "erreur": "utilisateur introuvable" } breaks everything that consumes it. The HTTP client never triggers its error path, the intermediate cache stores the response, monitoring counts a successful request, and the incident only surfaces when a human looks at a blank screen. The status code isn't decoration: it's the only part of your response that proxies, caches, browsers, and client libraries understand.
The second classic routing problem is structural. When all your routes are declared one after another in a single file, they end up stepping on each other: /utilisateurs/moi is captured by /utilisateurs/:id declared above it, and you spend an hour figuring out why the handler receives id === 'moi'. Express evaluates routes in declaration order, with no notion of specificity. This lesson covers both topics together, because well-structured routing is also routing whose order remains manageable.
Parameters, query, body
Three sources of input, three distinct uses.
// GET /api/v1/utilisateurs/42/commandes?statut=payee&page=2&taille=20
router.get('/:id/commandes', (req, res) => {
const { id } = req.params; // '42' — always a string
const { statut, page, taille } = req.query;
// ...
});
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion