tiangolo/fastapi · error · OwnerError

{username}

Error message

{username}

What it means

Identical to error 20 but in the non-`Annotated` parameter style (`username: str = Depends(get_username)`). An OwnerError carrying the username is raised when the resolved item's owner differs from the dependency-yielded identity, then translated to HTTP 400 by the yield dependency's except block.

Source

Thrown at docs_src/dependencies/tutorial008b_py310.py:29

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: 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 ("portal-gun").
  2. Return HTTP 403 with a clear detail from the handler instead of the opaque OwnerError.
  3. Replace the hardcoded `yield "Rick"` with a real auth dependency.
  4. Cover both owned and unowned item ids in tests.

Example fix

# before
if item["owner"] != username:
    raise OwnerError(username)

# after
if item["owner"] != username:
    raise HTTPException(status_code=403, detail="Forbidden: not the owner")
Defensive patterns

Strategy: validation

Validate before calling

if KNOWN_OWNERS[item_id] != "Rick":
    raise PermissionError("owner mismatch")

Type guard

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

Try / catch

r = client.get(f"/items/{item_id}")
if r.status_code == 400:
    detail = r.json().get("detail", "")
    if detail.startswith("Owner error:"):
        # pick another item
        ...

Prevention

When it happens

Trigger: GET /items/plumbus (owner="Morty") with username dependency yielding "Rick", tripping `if item["owner"] != username: raise OwnerError(username)`.

Common situations: Same as error 20; specifically seen when migrating tutorials from default-value Depends to Annotated Depends and the older form is still in use.

Related errors


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