Mapping URL parameters to server side logic
Types of Routes
- Static Routes
- Constant paths without variables (e.g.,
/api/books). - Always handle the same type of data or response pattern, regardless of input.
- Constant paths without variables (e.g.,
- Dynamic Routes
- Include variable parameters, often denoted with a colon (e.g.,
/api/users/:id). - The variable part is called a path parameter or route parameter, allowing requests like fetching a specific user by ID.
- Include variable parameters, often denoted with a colon (e.g.,
Query Parameters
- Key-value pairs appended after a ’?’ in the URL (e.g.,
/api/search?query=some+value). - Primarily used in GET requests (which lack a body) to send metadata.
- Common applications: search queries, pagination (e.g.,
?page=2&limit=20), filtering, and sorting (e.g., ascending/descending order).
Nested Routes
- Involve layering route segments for semantic clarity, often in REST APIs.
- Example:
/api/users/:userId/posts/:postIdto fetch a specific post from a specific user. - Each level adds hierarchy:
/api/usersfor all users,/api/users/:userIdfor one user, and so on, mapping to different handlers.
Route Versioning and Deprecation
- Incorporates version identifiers in paths (e.g.,
/api/v1/productsvs./api/v2/products). - Enables API evolution (e.g., changing response formats) without disrupting existing clients.
- Supports deprecation: Notify users to migrate from v1 to v2 over time, then retire the old version.
Catch-All Route
- A wildcard route (e.g.,
/*) that captures any unmatched paths. - Returns a user-friendly error message (e.g., “Route not found”) instead of a blank or null response.