Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Routing, handlers and responses, with no framework.
How does a basic server decide which function to call for a request?
A router matches a method and path to a handler. The handler builds a response from the matching route and whatever data the request carries.
Receive GET /reports/9
Look up GET and the report route and extract ID 9
The matching handler returns a response
Receive GET /reports/9
Look up GET and the report route and extract ID 9
The matching handler returns a response
Given Receive GET /reports/9 and The matching handler returns a response, write down the missing step that connects them.
Look up GET and the report route and extract ID 9
Now take Look up GET and the report route and extract ID 9 and the result above. Write an input and an implementation that could produce this trace.
Receive GET /reports/9. Check that your implementation produces the result shown above.
If the path exists for GET only, what should a POST to it return?
Return 405 Method Not Allowed and advertise the allowed methods. The resource path matched but the requested operation did not.
Check this when debugging. Returning 404 when the path exists but the method doesn't.
Frameworks like FastAPI and Flask feel like magic until you have built the core yourself. It is smaller than you would think: a loop that reads requests, a table of routes, and functions that return responses. Once you have written it, a framework's docs read like a list of conveniences on top of something you understand. It matters for AI work because a model behind an API is exactly this shape, one function from a request to a response, and every serving problem, a hung request, a missing header, a slow start, is easier to place when you know the loop.
A loop that reads requests, looks up a route and calls a function
A server waits for a request, matches its method and path against a table of routes, calls the matching function and sends back its response, then waits again. Frameworks add conveniences around that loop.
This rests on HTTP from the wire up, where you parsed a request from bytes. Picture a waiter in a small restaurant. They wait for someone to sit down and take the order, pass it to the kitchen, bring back the food, then wait for the next person. A web server does the same, forever:
Steps 1, 2 and 4 are plumbing, the same for every app. Step 3 is where your application lives, and it is an ordinary function from a request object to a response object. Here is the plumbing with Python's socket module (shown, not run: the academy's Python can't open ports).
import socket with socket.create_server(("127.0.0.1", 8000)) as server: while True: conn, addr = server.accept() # 1. wait for a client with conn: raw = conn.recv(65536) # 2. read the request response = handle(parse_request(raw)) # 3. YOUR app conn.sendall(response) # 4. send the answer
create_server opens a door on port 8000, and accept waits until someone knocks. Watch one request go through it.
Everything in a web framework is built around this loop.
Think of an office switchboard. A call comes in asking for sales, and the operator looks up the extension. The router does that job. Each route is a row in its table: a method, a path pattern and a handler. A pattern can hold path parameters in braces: /campaigns/{id} matches /campaigns/cmp_103 and captures id = "cmp_103". Matching works one segment at a time, a segment being the text between slashes. Literal segments must match exactly, {id} accepts any non-empty text, and paths with a different number of segments never match.
There are two different ways to be turned away. 404 Not Found means no pattern matches the path at all, as with the typo GET /campaings. 405 Method Not Allowed means the path matches but not with this method, as with DELETE /campaigns when only GET and POST exist there. A 405 must carry an Allow header listing the methods that work, such as Allow: GET, POST, so the client learns what it can do instead. Pick a case and watch the request leave at the right check.
GET /campaigns and POST /campaigns. A client sends DELETE /campaigns. Which status fits?405 Method Not Allowed, with an Allow header listing GET and POST
The path exists, so it is not 404. The method is not supported there, and the Allow header tells the client what is.
body = '{"name": "Café"}' print(len(body), len(body.encode("utf-8")))
16 17
The body has 16 characters, and the é takes two bytes in UTF-8, so it is 17 bytes on the wire. A server that read 16 would stop one byte short of the end of the JSON.
Write a sentence or two, then compare it with a good answer in the lesson.
Nobody wants to pick through raw bytes in every function, so parse the bytes once and pass around small objects. A handler is a function from a Request to a Response: one dish on the menu. The router below picks the handler.
Run the request and response as plain data, and read what each one holds.
The lesson runs this once, before its first cell, and every cell, drill and example starts with what it defines. A cell that changes a setup object changes it for the cells after it, until the page reloads.
import json CAMPAIGNS = {"cmp_1": {"id": "cmp_1", "name": "Spring sale", "budget": 500}} SEED = json.loads(json.dumps(CAMPAIGNS)) ROUTES = [] def route(method, pattern): def register(handler): ROUTES.append((method, pattern, handler)) return handler return register def match_pattern(pattern, path): p_parts, parts = pattern.strip("/").split("/"), path.strip("/").split("/") if len(p_parts) != len(parts): return None params = {} for p, a in zip(p_parts, parts): if p.startswith("{") and p.endswith("}"): if not a: return None params[p[1:-1]] = a elif p != a: return None return params @route("GET", "/campaigns") def list_campaigns(params, body): return 200, {"data": list(CAMPAIGNS.values())} @route("GET", "/campaigns/{id}") def get_campaign(params, body): c = CAMPAIGNS.get(params["id"]) return (200, c) if c else (404, {"error": f"no campaign {params['id']}"}) @route("POST", "/campaigns") def create_campaign(params, body): new_id = f"cmp_{len(CAMPAIGNS) + 1}" CAMPAIGNS[new_id] = {"id": new_id, **body} return 201, CAMPAIGNS[new_id] def handle(method, path, body=None): allowed = [] for m, pattern, handler in ROUTES: params = match_pattern(pattern, path) if params is None: continue if m == method: return handler(params, body) allowed.append(m) if allowed: return 405, {"error": "method not allowed", "allow": sorted(allowed)} return 404, {"error": "not found"}
from dataclasses import dataclass, field import json @dataclass class Request: method: str path: str query: dict = field(default_factory=dict) headers: dict = field(default_factory=dict) body: bytes = b"" def json(self): return json.loads(self.body or b"null") @dataclass class Response: status: int body: object = None headers: dict = field(default_factory=dict) def hello(req): name = req.query.get("name", "world") return Response(200, {"message": f"Hello, {name}!"}) print(hello(Request("GET", "/hello", query={"name": "Ada"})))
from dataclasses import dataclass @dataclass class Response: status: int body: object = None r = Response(404) print(r.status, r.body)
404 None
A dataclass field with a default keeps it when the caller leaves it out, so body is None. Handlers fill it in.
Write parse_query(query): turn "tag=rain&page=2&tag=sale" into {"tag": ["rain", "sale"], "page": ["2"]}. A name can repeat, so every value goes in a list; a pair with no = gets the value ""; empty pieces (from &&) are skipped. Decode each part with urllib.parse.unquote_plus.
Uses the setup above, 59 lines.
from urllib.parse import unquote_plus def parse_query(query): return dict(pair.split("=") for pair in query.split("&")) print(parse_query("tag=rain&page=2&tag=sale"))
The lesson's setup holds a complete tiny API: a @route decorator that adds a handler to the table (decorators are from Closures and decorators), match_pattern from the picture above, and handle, which tries each route. A path match with the wrong method is noted for the 405, and no match at all is a 404.
Three handlers and a handle function, with no framework. The data lives in a dict standing in for a database.
Uses the setup above, 59 lines.
CAMPAIGNS.clear() CAMPAIGNS.update(SEED) print(handle("POST", "/campaigns", {"name": "Autumn", "budget": 300})) print(handle("GET", "/campaigns/cmp_2")) print(handle("DELETE", "/campaigns")) print(handle("GET", "/campaings"))
@route(...) ran when each handler was defined and added it to the route table. The POST made cmp_2, the GET found it, the DELETE got a 405 that lists the allowed methods, and the typo got a 404.
The stepper runs the routing loop on the 405 case. Watch allowed fill as the loop passes a pattern that matches the path, and watch the else branch run only because the loop never hit break.
routes = {"/items": ["GET"]}
path, method = "/items", "DELETE"
if path not in routes: print(404)
elif method not in routes[path]: print(405)
else: print(200)405
The path exists, but not with that method, so it is 405 rather than 404.
Any lamp works in any wall socket, because everyone agreed on the shape of the plug. Python web servers and frameworks agreed on one for step 3, so any server can run any framework. WSGI is the classic plug: an app is a function app(environ, start_response). environ is a dict describing the request, and the app calls start_response(status, headers) and returns a list of body bytes. Flask and Django speak WSGI, and Gunicorn runs them.
Both speak WSGI, the standard interface between Python servers and apps
WSGI (and ASGI for async apps) is the agreed plug shape, so any server can run any framework that speaks it.
ASGI is the newer one, for async code, and FastAPI, Starlette and Uvicorn speak it. An ASGI app is an async function of three arguments: scope, a dict that describes the connection (its type, method and path); receive, an async function that returns the next piece of the request; and send, an async function the app calls with each piece of the reply. A reply is at least two messages, http.response.start (status and headers) and http.response.body. Because the app awaits receive and send, one process can hold thousands of open connections, including streams, and it can send a body in several pieces. Streaming from the server uses that.
Both are plain function calls, which is why a server's job is small and why test clients exist: they call your app the same way. Here is each one called by hand, with a fake receive and send for ASGI. (asyncio.run works on browsers with JSPI and in the validator; older browsers can't run the ASGI cell.)
Run the app once with a fake WSGI environment, the way a real server would call it.
Uses the setup above, 59 lines.
from wsgiref.util import setup_testing_defaults def wsgi_app(environ, start_response): body = f"You asked for {environ['PATH_INFO']}".encode() headers = [("Content-Type", "text/plain"), ("Content-Length", str(len(body)))] start_response("200 OK", headers) return [body] environ = {"PATH_INFO": "/campaigns", "REQUEST_METHOD": "GET"} setup_testing_defaults(environ) captured = {} result = wsgi_app(environ, lambda s, h: captured.update(status=s, headers=h)) print(captured["status"], b"".join(result))
Uses the setup above, 59 lines.
import asyncio async def asgi_app(scope, receive, send): assert scope["type"] == "http" body = f"You asked for {scope['path']}".encode() await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]}) await send({"type": "http.response.body", "body": body}) sent = [] async def fake_receive(): return {"type": "http.request", "body": b"", "more_body": False} async def fake_send(message): sent.append(message) scope = {"type": "http", "method": "GET", "path": "/campaigns"} asyncio.run(asgi_app(scope, fake_receive, fake_send)) print([m["type"] for m in sent], sent[1]["body"])
Any WSGI server can run a function shaped like app(environ, start_response). Write one: for GET /health, call start_response("200 OK", [("Content-Type", "application/json")]) and return [b'{"ok": true}']; for any other path, start "404 Not Found" with the same header and return [b'{"error": "not found"}']. The method is environ["REQUEST_METHOD"] and the path environ["PATH_INFO"].
Uses the setup above, 59 lines.
def app(environ, start_response): start_response("200 OK", []) return ["ok"] calls = [] print( app( {"REQUEST_METHOD": "GET", "PATH_INFO": "/health"}, lambda status, headers: calls.append(status), ), calls, )
await send({"type": "http.response.body", "body": b"hi"}) do?Sends a piece of the reply body to the client
send carries the reply out, one message at a time. The start message sends the status and headers, and each body message sends bytes. receive is the one that reads the request.
scope, receive and send in an ASGI app?Write a sentence or two, then compare it with a good answer in the lesson.
A production server wraps your app in the same loop with more staff: many workers (copies of the process), time limits, limits on body size and protection from slow clients. You don't write those parts. You plug your app into Gunicorn (WSGI) or Uvicorn (ASGI). A model behind an API is one more handler, a function from a request to a response, so the lessons about routing, 404 and 405 apply to POST /predict exactly as to GET /campaigns.
The picture shows where this lesson sits in a service. Then you call the server you just wrote.
serve(app) from the academy's devserver takes a WSGI or ASGI callable and returns the address to call it at, so requests reaches the app you built. Wrap handle in a WSGI function and call it over HTTP. It is a development server: one request at a time, no TLS.
Uses the setup above, 59 lines.
import json import requests from devserver import serve def app(environ, start_response): length = int(environ.get("CONTENT_LENGTH") or 0) raw = environ["wsgi.input"].read(length) if length else b"" body = json.loads(raw) if raw else None status, data = handle(environ["REQUEST_METHOD"], environ["PATH_INFO"], body) payload = json.dumps(data).encode() phrases = {200: "OK", 201: "Created", 404: "Not Found", 405: "Method Not Allowed"} headers = [("Content-Type", "application/json")] start_response(f"{status} {phrases[status]}", headers) return [payload] base = serve(app) print(requests.get(f"{base}/campaigns/cmp_1").json()) r = requests.delete(f"{base}/campaigns") print(r.status_code, r.json())
The DELETE got its 405 over a real HTTP call. That tiny server did the loop's four steps on every call. The wrapper above does not yet add the Allow header your 405 owes the client, which is the exercise's job.
Three habits come from this lesson. Answer 404 and 405 correctly: it tells a developer at once whether they misspelled the URL or used the wrong verb. Check your path patterns: /items/{id} must not match /items/, or a handler receives an empty id and may list or delete the wrong thing. Test without a network: an app is a function, so call it directly, which runs thousands of times faster than a real server and cannot fail because a port is busy. Keep a few real end-to-end tests and do the rest this way.
Goes deeper in: A web framework, from the inside builds middleware and decorators on this router, APIs with FastAPI replaces it, and System design fundamentals adds the load balancer in front of many workers.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What is the difference between a 404 and a 405?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write