Web & Internet
REST API Routing
O(number of routes) to find a match in this simple version. Real frameworks use faster lookup structures, but the matching idea is the same.
The idea, in plain English
An API (Application Programming Interface) is the menu of things a server lets other programs ask for. A REST API organizes requests by combining a method, like GET or POST, with a path, like /users/1. Routing is the server's job of matching that combination against a list of known routes, then calling the right handler. It's like a receptionist reading your appointment slip and pointing you to the right department.
How it works
- 1The server keeps a list of routes it knows about. Each one pairs a method and path pattern with a handler function.
- 2When a request comes in, split its path into pieces and compare them to each route's pattern, piece by piece.
- 3A piece like :id in the pattern is a placeholder. It matches anything and captures that value as a parameter.
- 4The first route that fully matches handles the request. If nothing matches, the server answers with a 404.
When you'd use it
This applies when building any REST API, a common style for web services. Each resource gets one URL (Uniform Resource Locator) path, and each action gets one method, like GET /users/1 to fetch and POST /users to create.
Common beginner mistakes
- Don't forget that the method matters as much as the path. GET /users and POST /users are two different routes, even though the path looks the same.
- Watch the order of routes when patterns overlap. A very general pattern placed before a specific one can accidentally catch requests meant for the specific one.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
GET /users -> list of all users
GET /users/1 -> user #1
POST /users -> created a new user
DELETE /users/1 -> 404 Not FoundNot sure this is the right topic? See the learning paths → or where this leads →