tiangolo/fastapi · error · HTTPException
Item already exists
Error message
Item already exists
What it means
Non-Annotated variant of error 3: POST /items/ raises HTTP 409 "Item already exists" when the body's id is already a key in fake_db.
Source
Thrown at docs_src/app_testing/app_b_py310/main.py:34
title: str
description: str | None = None
@app.get("/items/{item_id}", response_model=Item)
async def read_main(item_id: str, x_token: str = Header()):
if x_token != fake_secret_token:
raise HTTPException(status_code=400, detail="Invalid X-Token header")
if item_id not in fake_db:
raise HTTPException(status_code=404, detail="Item not found")
return fake_db[item_id]
@app.post("/items/")
async def create_item(item: Item, x_token: str = Header()) -> Item:
if x_token != fake_secret_token:
raise HTTPException(status_code=400, detail="Invalid X-Token header")
if item.id in fake_db:
raise HTTPException(status_code=409, detail="Item already exists")
fake_db[item.id] = item.model_dump()
return item
View on GitHub (pinned to 42a41db11f)
Solutions
- Generate a unique id (uuid4) per create.
- Treat 409 as a signal to fetch/update instead of create.
- Pre-check existence with a GET.
Example fix
# before
payload = {"id": "foo", ...}
# after
payload = {"id": str(uuid.uuid4()), ...} Defensive patterns
Strategy: validation
Validate before calling
import uuid
payload = {"id": str(uuid.uuid4()), "title": "Baz"} Type guard
def is_unique_id(new_id: str, existing: set[str]) -> bool:
return new_id not in existing Try / catch
resp = client.post("/items/", json=payload, headers=auth)
if resp.status_code == 409:
client.get(f"/items/{payload['id']}", headers=auth) Prevention
- Use unique ids per create.
- Idempotency keys on retries.
- On 409, fetch instead of re-create.
When it happens
Trigger: POST /items/ with an id colliding with an existing entry.
Common situations: Duplicate POST/retry; double-seeding; non-unique client ids.
Related errors
AI-assisted analysis of tiangolo/fastapi@42a41db11f (2026-08-04).
Data as JSON: /data/errors/f2bd8c6e63b061ed.json.
Report an issue: GitHub.