How the Web Works Checkpoint
25 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
A real server reads a request, checks the method, the headers and the cookie, and answers with the right status code. This checkpoint builds that flow in small steps and then tests the whole module.
Read a request from the top
Split the raw text at the first blank line. The first line gives the method and path. The lines after it are headers. The rest is the body.
raw = "GET /items HTTP/1.1\r\nHost: a.com\r\n\r\n"head, body = raw.split("\r\n\r\n", 1)request_line, *header_lines = head.split("\r\n")print(request_line.split()[0])This prints GET. Every server framework does this work before your code runs.
Pick the status code on purpose
Ask three questions in order. Is the caller known? Is the caller allowed? Is the request itself valid? The answers lead to 401, 403 and 400 or 422. Success follows: 200, 201 or 204.
def check(token, role): if token is None: return 401 if role != "admin": return 403 return 200Example 1 · A tiny request handler
from http import HTTPStatus
TOKENS = {"t-admin": "admin", "t-user": "customer"}
def handle(raw): head, _, body = raw.partition("\r\n\r\n") first, *lines = head.split("\r\n") method, path, _ = first.split() headers = {k.lower(): v for k, v in (l.split(": ", 1) for l in lines)} if method not in ("GET", "POST"): return HTTPStatus.METHOD_NOT_ALLOWED scheme, _, token = headers.get("authorization", "").partition(" ") role = TOKENS.get(token) if scheme == "Bearer" else None if role is None: return HTTPStatus.UNAUTHORIZED if path.startswith("/admin") and role != "admin": return HTTPStatus.FORBIDDEN return HTTPStatus.OK
def request(method, path, token=None): auth = f"Authorization: Bearer {token}\r\n" if token else "" return f"{method} {path} HTTP/1.1\r\nHost: a.com\r\n{auth}\r\n"
print(handle(request("GET", "/items", "t-user")))print(handle(request("GET", "/items")))print(handle(request("GET", "/admin/users", "t-user")))print(handle(request("DELETE", "/items", "t-admin")))200 401 403 405
What this code does
- The handler asks its questions in order: method, then identity, then permission.
- Printing an
HTTPStatusshows its number, because it is an integer type.
A missing login is 401. A known user without the right role is 403.
Know what HTTPS covers
HTTPS protects the request line, headers, cookies and body while they travel. It does not make your code correct, and it does not hide the server name completely. Keep certificate checks on.
import ssl
ctx = ssl.create_default_context()print(ctx.check_hostname, ctx.verify_mode == ssl.CERT_REQUIRED)Example 2 · Cookies and counting visits
from fastapi import Cookie, FastAPI, Responsefrom fastapi.testclient import TestClient
app = FastAPI()
@app.get("/hello")def hello(response: Response, visits: int = Cookie(default=0)): response.set_cookie("visits", str(visits + 1), httponly=True) return {"visits": visits + 1}
client = TestClient(app)for _ in range(3): print(client.get("/hello").json())client.cookies.clear()print(client.get("/hello").json()){'visits': 1}
{'visits': 2}
{'visits': 3}
{'visits': 1}What this code does
- The test client sends the cookie back, like a browser.
- After the cookies are cleared, the server sees a new visitor.
Both checks are on by default. Leave them on.
Finish up
Mark complete & continue
Next: Resources and URLs