{"id":"4f570283ed13aa64","repo":"tiangolo/fastapi","slug":"item-already-exists","errorCode":null,"errorMessage":"Item already exists","messagePattern":"Item already exists","errorType":"http","errorClass":"HTTPException","httpStatus":409,"severity":"error","filePath":"docs_src/app_testing/app_b_an_py310/main.py","lineNumber":36,"sourceCode":"    title: str\n    description: str | None = None\n\n\n@app.get(\"/items/{item_id}\", response_model=Item)\nasync def read_main(item_id: str, x_token: Annotated[str, Header()]):\n    if x_token != fake_secret_token:\n        raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")\n    if item_id not in fake_db:\n        raise HTTPException(status_code=404, detail=\"Item not found\")\n    return fake_db[item_id]\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item, x_token: Annotated[str, Header()]) -> Item:\n    if x_token != fake_secret_token:\n        raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")\n    if item.id in fake_db:\n        raise HTTPException(status_code=409, detail=\"Item already exists\")\n    fake_db[item.id] = item.model_dump()\n    return item\n","sourceCodeStart":18,"sourceCodeEnd":39,"githubUrl":"https://github.com/tiangolo/fastapi/blob/42a41db11f6882807ac3c057b942178d53b97438/docs_src/app_testing/app_b_an_py310/main.py#L18-L39","documentation":"Raised by POST /items/ when the submitted Item's id already exists as a key in fake_db, returning HTTP 409 Conflict. It enforces uniqueness of item ids and prevents duplicate creation.","triggerScenarios":"POST /items/ with a JSON body whose id field equals an existing key (\"foo\" or \"bar\", or any previously created id).","commonSituations":"Retrying a POST after a timeout that actually succeeded; duplicate-submit; seeding scripts run twice; client generating ids that collide.","solutions":["Use a unique id for each create (e.g. uuid4).","On 409, GET the existing item instead of re-posting.","Make the client idempotent by checking existence before creating."],"exampleFix":"# before\nitem_id = \"foo\"  # already exists\n# after\nimport uuid\nitem_id = str(uuid.uuid4())","handlingStrategy":"validation","validationCode":"# Generate a unique id to avoid collisions\nimport uuid\npayload = {\"id\": str(uuid.uuid4()), \"title\": \"Baz\"}","typeGuard":"def is_unique_id(new_id: str, existing: set[str]) -> bool:\n    return new_id not in existing","tryCatchPattern":"resp = client.post(\"/items/\", json=payload, headers=auth)\nif resp.status_code == 409:\n    # already exists; fetch instead\n    client.get(f\"/items/{payload['id']}\", headers=auth)","preventionTips":["Use server- or UUID-generated ids for creates.","Make POST retries idempotent with an idempotency key.","On 409, switch to a GET/update flow."],"tags":["fastapi","conflict","duplicate","httpexception"],"analyzedSha":"42a41db11f6882807ac3c057b942178d53b97438","analyzedAt":"2026-08-04T19:23:32.007Z","schemaVersion":2}