tiangolo/fastapi · error · HTTPException

Owner error

Error message

Owner error: {e}

What it means

This is an HTTPException (status 400) raised inside a yield-based FastAPI dependency. The dependency get_username yields 'Rick', and the path operation raises a custom OwnerError when the requested item's owner does not match the yielded username. FastAPI routes exceptions thrown after a yield back into the dependency's except block, which converts OwnerError into a 400 HTTPException. It exists to demonstrate converting a domain/ownership exception into an HTTP error at the dependency boundary.

Solutions

  1. Confirm which item you requested and compare its 'owner' field against the username the dependency yields (here 'Rick'); request an item owned by that user.
  2. If the yielded username should be dynamic, replace the hard-coded yield 'Rick' with real user resolution (e.g. from a token/session) so ownership matches.
  3. Move the ownership check into the path operation and raise HTTPException(400) directly instead of relying on the yield-dependency except bridge, to make the failure explicit.

Example fix

// before
def get_username():
    try:
        yield "Rick"
    except OwnerError as e:
        raise HTTPException(status_code=400, detail=f"Owner error: {e}")
// after (dynamic user + explicit HTTP error)
def get_username(token: str = Depends(oauth2_scheme)):
    user = resolve_user(token)
    if not user:
        raise HTTPException(status_code=401, detail="Not authenticated")
    try:
        yield user.username
    except OwnerError as e:
        raise HTTPException(status_code=400, detail=f"Owner error: {e}")
Defensive patterns

Strategy: try-catch

Validate before calling

import requests
item = 'portal-gun'
# verify ownership locally before calling
known_owner = {'plumbus': 'Morty', 'portal-gun': 'Rick'}
if known_owner.get(item) != 'Rick':
    print('will fail with Owner error')

Type guard

def is_owned_by(username: str, item_id: str, data: dict) -> bool:
    return item_id in data and data[item_id].get('owner') == username

Try / catch

import requests
resp = requests.get('http://localhost:8000/items/plumbus')
try:
    resp.raise_for_status()
except requests.HTTPError as e:
    if resp.status_code == 400 and 'Owner error' in resp.text:
        print('Ownership check failed:', resp.json()['detail'])
    else:
        raise

Prevention

When it happens

Trigger: GET /items/portal-gun with no special handling: 'portal-gun' is in the data dict (owner 'Rick'), so ownership check passes. The trigger is requesting an item whose owner != 'Rick' — but in this sample data both items are owned by Morty/Rick, so the real trigger is any item_id present in `data` whose 'owner' value differs from the hard-coded yielded 'Rick'. Concretely, GET /items/plumbus returns 400 because owner is 'Morty' while yielded username is 'Rick'.

Common situations: Building authorization/ownership checks via dependencies and needing to translate a non-HTTP exception raised downstream into a clean 400 response. Developers hit this when the yielded identity (hard-coded here) does not match the data's stored owner, or when they forget that the yield-dependency except block is the only place to catch downstream OwnerError.

Related errors


AI-assisted analysis of tiangolo/fastapi@3e8d1526d8 (2026-08-11). Data as JSON: /api/errors/fc01ee80af6d9930. Report an issue: GitHub.

Appendix: source

Thrown at docs_src/dependencies/tutorial008b_py310.py:20

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: 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 3e8d1526d8)