Routing by Hand, and Why Frameworks Exist

A plain Python function can answer requests by checking each one's method and path with if statements and returning a status code and a body, and seeing that code grow with every route shows the jobs a framework such as FastAPI takes over.

Apprentice · REST API · Web Development · Python · Updated

By

After this lesson you can

  • Write a function that routes a request by its method and path and returns a status code and a body, with 404 and 405 for requests it doesn't answer
  • Explain the jobs a web framework such as FastAPI takes over from hand-written routing, such as matching paths, checking values and sending JSON

Key takeaways

  • Routing is choosing which code answers a request, from its method and its path. By hand, it's an if statement for each route.
  • A function can give back a status code and a body together as a tuple, such as return 404, {"detail": "Not Found"}.
  • Reading a number from a path by hand means cutting the path apart, checking the text is a number, and answering 400 when it isn't.
  • A path the API has, asked with a method it doesn't take, gets 405 Method Not Allowed. Any other unknown address gets 404.
  • A framework such as FastAPI takes over the routing, the reading and checking of values, the JSON and the docs, so you write only what each route does.

Every web framework you'll meet, FastAPI, Flask, Django or Express, starts each request the same way: it looks at the method and the path and picks the function that answers. Doing that job by hand once, in plain Python, pays off in every lesson after it: you'll know what FastAPI is doing for you, and why it answers 404 ("there's nothing at that address"), 405 or 422 when you didn't write any code for them.

The example is the Greenleaf Community Garden's API, built with no framework at all: one function that takes a request's method and path and gives back an answer.

A function that answers requests

The garden's API has to answer GET /plots with every plot, and anything it doesn't know with a 404. Here is that much in plain Python:

PLOTS = [
    {"number": 1, "size": "small", "gardener": "Rosa", "growing": "tomatoes"},
    {"number": 2, "size": "large", "gardener": None, "growing": None},
    {"number": 7, "size": "small", "gardener": "Lena", "growing": "strawberries"},
]


def handle(method, path):
    if method == "GET" and path == "/plots":
        return 200, PLOTS
    return 404, {"detail": "Not Found"}


status, body = handle("GET", "/plots")
print(status, len(body))
print(handle("GET", "/tools"))
200 3
(404, {'detail': 'Not Found'})

return 200, PLOTS gives back two values at once, a status code and a body. Values given back together like that are a tuple, which Python prints in round brackets. status, body = handle(...) unpacks it, putting the first value in status and the second in body.

Choosing which code answers a request, from its method and its path, is called routing, and each if here is one route.

One plot, by its number

"Who has plot 7?" is GET /plots/7, and the garden can't write an if for every number. The route has to cut the number off the end of the path, check that it is a number, and turn the text into one:

def handle(method, path):
    if method == "GET" and path == "/plots":
        return 200, PLOTS
    if method == "GET" and path.startswith("/plots/"):
        number_text = path.removeprefix("/plots/")
        if not number_text.isdigit():
            return 400, {"detail": "A plot number is a whole number."}
        number = int(number_text)
        for plot in PLOTS:
            if plot["number"] == number:
                return 200, plot
        return 404, {"detail": f"There's no plot {number}."}
    return 404, {"detail": "Not Found"}


print(handle("GET", "/plots/7"))
print(handle("GET", "/plots/9"))
print(handle("GET", "/plots/seven"))
(200, {'number': 7, 'size': 'small', 'gardener': 'Lena', 'growing': 'strawberries'})
(404, {'detail': "There's no plot 9."})
(400, {'detail': 'A plot number is a whole number.'})

startswith checks how the path begins, removeprefix cuts that beginning off and leaves "7", and isdigit() is True only when the text is all digits. Text such as seven gets a 400: the request has a problem, and the message says what it is.

Every route makes it longer

Two routes took thirteen lines, and the function still gets things wrong:

  • DELETE /plots/7 answers 404 Not Found, but /plots/7 is there; it's the method the API doesn't take. That answer is 405 Method Not Allowed, and every path needs a check for it.
  • GET /plots?free=true answers 404 too, because "/plots?free=true" isn't "/plots". The query string has to be split off first, with urlsplit and parse_qs from HTTP in Plain Words: Requests and Responses, and "true" turned into True.
  • The body is still a Python list. Before it can travel, it has to become JSON text, with a Content-Type: application/json header beside it.

A real API has dozens of routes, and each one needs the same cutting, checking and converting. Most of the code would be about HTTP, not about the garden.

The jobs a framework takes over

A framework is a large set of ready-made code that runs your app and calls the parts you write. A web framework does the HTTP work, and you write only what each route does. Here is plot 7's route the way you'll write it in FastAPI, starting in the next chapter:

@app.get("/plots/{number}")
def get_plot(number: int):
    for plot in PLOTS:
        if plot["number"] == number:
            return plot
    raise HTTPException(status_code=404, detail=f"There's no plot {number}.")

The decorator, @app.get(...), is the if for the method and the path, and {number} marks where the number sits. Here is what FastAPI does for you:

Job By hand In FastAPI
Pick the function An if for each method and path A decorator such as @app.get("/plots/{number}")
Read and check the number removeprefix, isdigit(), int(), your own 400 The type hint number: int, and a 422 for seven
Read the query string urlsplit, parse_qs, turn "true" into True A function parameter, such as free: bool
A path with the wrong method Your own 405 for every path 405, by itself
Send JSON Turn the body into JSON text, set Content-Type Return a dictionary or a list
Tell people how to call it Write a manual The /docs page, made from your code

FastAPI's answer to seven is 422, not 400: it reads the request, but the value breaks the rule int. The idea is the same as yours. The difference is that you never write it.

Do it: answer the garden's requests by hand

The garden's front desk wants a small API in plain Python. It answers three addresses, /, /plots and /gardeners, all with GET. PLOTS is in the code already.

  • method: the request's method in capital letters, such as "GET" or "POST".
  • path: the request's path, such as "/plots".

Your job: write the function handle(method, path) so it returns a tuple of a status code and a body:

  • GET / answers 200 with {"message": "Welcome to Greenleaf Community Garden"}.
  • GET /plots answers 200 with PLOTS.
  • GET /gardeners answers 200 with a list of the gardeners' names, in the order of PLOTS, skipping the plots that have no gardener (None).
  • Any other method for those three paths, such as POST /plots, answers 405 with {"detail": "Method Not Allowed"}.
  • Any other path answers 404 with {"detail": "Not Found"}.

Worked through: handle("GET", "/gardeners") goes through PLOTS: plot 1's gardener is Rosa, plot 2 has None and is skipped, and plot 7's is Lena. It returns (200, ["Rosa", "Lena"]).

Practiced live on the lesson page: write the Python right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Routing by hand shows what every request needs before your code can answer it, and that is exactly the work FastAPI does for you, so you can spend your lines on the garden instead of on HTTP.

Key terms

Related