PythiloLesson 5 of 14 · progress kept in this browser

Turn a missing resource into HTTP 404

An expected domain failure should become an intentional HTTP response. Raising HTTPException stops the endpoint and gives FastAPI a status and a JSON detail. An uncaught KeyError instead describes a server implementation error and usually becomes a server failure.

Keep successful and missing-resource paths explicit. Do not catch every exception and report 404, since that would hide programming errors and broken dependencies. Testing both paths through the application also verifies that the framework's exception handler, rather than an ordinary Python return value, creates the response.

from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{key}")
async def read(key: int):
    if key != 1:
        raise HTTPException(404, "not found")
    return {"key": key}
print(app.openapi()["paths"].keys())
Your task

Implement build_app() serving GET /items/{key}. Only key 1 exists and returns {"name":"Tea"}. Any other integer returns 404 with detail "not found"; a noninteger key returns 422.

The first run loads fastapi, httpx into this browser.