tiangolo/fastapi · error · HTTPException

Owner error: {e}

Error message

Owner error: {e}

What it means

Raised inside the get_username generator dependency when it catches an OwnerError thrown by the route after the dependency yielded. FastAPI re-enters the generator to deliver the exception; the dependency translates it into HTTP 400 with detail f"Owner error: {e}". This demonstrates using a yield-dependency both to provide a value and to centralize error handling for a domain-specific exception.

Source

Thrown at docs_src/dependencies/tutorial008b_an_py310.py:22

app = FastAPI()


data = {
    "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
    "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
}


class OwnerError(Exception):
    pass


def get_username():
    try:
        yield "Rick"
    except OwnerError as e:
        raise HTTPException(status_code=400, detail=f"Owner error: {e}")


@app.get("/items/{item_id}")
def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
    if item_id not in data:
        raise HTTPException(status_code=404, detail="Item not found")
    item = data[item_id]
    if item["owner"] != username:
        raise OwnerError(username)
    return item

View on GitHub (pinned to 42a41db11f)

Solutions

  1. Request an item owned by the yielded user ("Rick"), e.g. /items/portal-gun.
  2. If ownership is legitimate, change the yielded username or the data's owner to align.
  3. Handle the 400 response by informing the user they lack ownership.

Example fix

# before
client.get("/items/plumbus")  # owner is Morty
# after
client.get("/items/portal-gun")  # owner is Rick
Defensive patterns

Strategy: try-catch

Validate before calling

# Only request items owned by the current user ("Rick")
owned_by_rick = {"portal-gun"}
if item_id in owned_by_rick:
    client.get(f"/items/{item_id}")

Type guard

def owned_by_user(item: dict, user: str) -> bool:
    return item.get("owner") == user

Try / catch

resp = client.get(f"/items/{item_id}")
if resp.status_code == 400 and "Owner error" in resp.json().get("detail", ""):
    # current user does not own this item
    ...

Prevention

When it happens

Trigger: GET /items/{item_id} where the item exists and is valid (so no 404) but item["owner"] != "Rick" (the yielded username). For example, GET /items/plumbus whose owner is "Morty".

Common situations: Accessing a resource owned by another user; assuming the current user matches the owner; logic errors where the yielded username is wrong.

Related errors


AI-assisted analysis of tiangolo/fastapi@42a41db11f (2026-08-04). Data as JSON: /data/errors/0e901746b13c342a.json. Report an issue: GitHub.