PythiloLesson 9 of 14 · progress kept in this browser

Add a response header in middleware

Middleware wraps request handling and can observe or modify responses across several routes. An HTTP middleware function receives the request and calls the next application layer. It can then add a header to the returned response.

Always return the response after changing it, and keep unrelated business logic inside endpoints or dependencies. This example uses a fixed application marker instead of a clock-based timing header, so its behaviour is deterministic. Requests still pass through the real middleware stack when HTTPX uses an in-memory ASGI transport.

from fastapi import FastAPI
app = FastAPI()
@app.middleware("http")
async def marker(request, call_next):
    response = await call_next(request)
    response.headers["X-Lesson"] = "yes"
    return response
print(len(app.user_middleware))
Your task

Implement build_app() with GET /ping returning {"ok":True}. HTTP middleware must add X-Course: pythilo to every response, including a 404 response.

The first run loads fastapi, httpx into this browser.