Path, query, and HTTPException

Your POST takes a body. Now we need the rest of the HTTP vocabulary: path parameters for identifying a resource, query parameters for filtering, status codes that mean something, and HTTPException for when things go wrong. FastAPI handles each of these with the same type-hint trick.

router.py
python
from fastapi import APIRouter, HTTPException

@router.get("/status/{url:path}", status_code=200)
async def get_processing_status(url: str, include_debug: bool = False):
    """Return the status of a previously submitted URL."""
    if url not in processing_status:
        raise HTTPException(status_code=404, detail="URL not found")
    data = processing_status[url]
    if not include_debug:
        data = {k: v for k, v in data.items() if k != "debug"}
    return data

The url parameter is a path parameter because it appears in the route pattern. include_debug is a query parameter because it is a plain function argument with a default. HTTPException short-circuits with a clean JSON error.

Three patterns to notice. First, the path parameter name inside the braces has to match the function argument name. Second, a function argument with a default value becomes a query parameter, so you call it as ?include_debug=true. Third, raising HTTPException anywhere inside the handler produces a proper HTTP error response with a JSON body.

No. The default is 200. Set status_code when you want to be explicit, like 201 Created for a successful POST, or 204 No Content for a DELETE that returns nothing. For errors, raise HTTPException with the right code and FastAPI formats the response.

Quiz: Quiz

Loading practice…

Checkpoint: First endpoints checkpoint

Loading practice…