How a Web Framework Routes a Request to Your Code
When you write a web application with a framework, a request arrives and, as if by magic, the right function runs. You write a function for the path /users/42, and the framework finds it, hands over the number 42 and sends back whatever you return. It seems simple from the outside, yet a clear chain of steps sits behind it.
Understanding that chain makes frameworks feel less mysterious. It also makes errors such as unexpected 404 responses and missing parameters far easier to track down.
The Starting Point
By the time your framework sees a request, the web server has already done the low-level work of accepting the connection and reading the bytes. The framework receives a structured description of the request: the HTTP method, the path, query string, headers and body.
Different ecosystems standardize this hand-off. Python has interfaces named WSGI and ASGI, Ruby has Rack and Java has the servlet specification. They define a common shape so that servers and frameworks can be mixed and matched. In Node.js, the server gives the framework a request object and a response object.
The Routing Table
At startup, you register routes. Each route pairs a method and a URL pattern with a handler function.
@app.get("/users/<int:user_id>")
def show_user(user_id):
return {"id": user_id}
@app.post("/users")
def create_user():
return {"created": True}, 201
The framework stores these registrations in a data structure, often called the routing table. Behind the scenes, patterns are compiled into a form that can be matched quickly, commonly regular expressions or a tree where each segment of the path is a branch.
Some frameworks register routes through decorators like the ones above. Others use a central configuration file, a naming convention based on file locations or annotations on classes. The end result is the same: a lookup structure from patterns to handlers.
Matching a Request
When a request arrives, the framework compares its method and path against the table. The steps usually run like this.
- Check the method. A GET request will not match a route registered only for POST.
- Walk through patterns, or descend the path tree, to find one that fits.
- Extract the dynamic parts of the path.
- If nothing matches, return a 404 response. If the path matches but not the method, many frameworks return a 405.
For /users/42, the pattern /users/<int:user_id> matches, and the framework captures the text 42. If the pattern declares an integer type, the framework converts it, and rejects the match if the text cannot be converted.
Order can matter. In some frameworks, the first matching pattern wins, so a broad pattern placed too early can swallow requests meant for a more specific one. Most modern routers rank specific routes above general ones automatically, but check your framework's rules.
Parameters and Input
Your handler can receive input from several places.
- Path parameters: the variable parts of the URL, such as the user identifier.
- Query parameters: values after the question mark, like
?page=2. - Headers: metadata such as authorization tokens.
- Body: form data or JSON in a POST or PUT request.
Frameworks parse these for you and make them available through a request object or as arguments to your function. Many also validate types, so a malformed value produces a clear client error before your code runs.
Middleware
Between the raw request and your handler sit middleware components. Each one wraps the next, forming a pipeline. A request passes inward through the layers, reaches the handler and then the response travels back out through the same layers in reverse.
Typical middleware tasks include:
- Logging each request and its duration.
- Checking a session or token and attaching the current user.
- Applying cross-origin rules and security headers.
- Compressing responses.
- Catching exceptions and converting them into error responses.
A middleware can also stop the chain early. An authentication layer, for instance, can return a 401 response without ever calling the handler.
Running the Handler and Building the Response
Once middleware is done, the framework calls your handler with the extracted arguments. Your function returns something: a string, a dictionary, a template result or a response object.
The framework converts that return value into a proper HTTP response. A dictionary may become JSON with the right content type header. A string becomes an HTML body. If you need control, you can return a response object with a chosen status code and headers.
Finally, the response passes back through middleware and goes to the server, which sends it to the client.
Debugging Routing Problems
Knowing the process helps you troubleshoot.
- Unexpected 404: check for a trailing slash difference, a typo in the pattern or a route registered after a catch-all route.
- 405 errors: confirm the method matches the route definition.
- Wrong handler called: look for overlapping patterns and their order.
- Parameter not arriving: verify that the name in the pattern matches the function argument.
- Most frameworks provide a command or debug page that lists all registered routes. Use it.
Frequently Asked Questions
What is the difference between routing and middleware?
Routing decides which handler should process a request, based on method and path. Middleware wraps the whole process and applies shared behavior, such as logging or authentication, to many routes at once.
Why do I get a 404 for a path that exists?
Common causes are a trailing slash mismatch, a route registered with a different method, a typo or a prefix that was not applied. Listing the registered routes usually reveals the difference quickly.
Do all frameworks route requests the same way?
The broad idea is shared, but details vary. Some match patterns in order, others use a tree, and some derive routes from file names. The observable behavior of matching a path and calling a handler stays the same.