{"record":{"id":"94b1e6047b5c8990","repo":"tiangolo/fastapi","slug":"invalid-yaml","errorCode":null,"errorMessage":"Invalid YAML","messagePattern":"Invalid YAML","errorType":"http","errorClass":"HTTPException","httpStatus":422,"severity":"error","filePath":"docs_src/path_operation_advanced_configuration/tutorial007_py310.py","lineNumber":27,"sourceCode":"    name: str\n    tags: list[str]\n\n\n@app.post(\n    \"/items/\",\n    openapi_extra={\n        \"requestBody\": {\n            \"content\": {\"application/x-yaml\": {\"schema\": Item.model_json_schema()}},\n            \"required\": True,\n        },\n    },\n)\nasync def create_item(request: Request):\n    raw_body = await request.body()\n    try:\n        data = yaml.safe_load(raw_body)\n    except yaml.YAMLError:\n        raise HTTPException(status_code=422, detail=\"Invalid YAML\")\n    try:\n        item = Item.model_validate(data)\n    except ValidationError as e:\n        raise HTTPException(status_code=422, detail=e.errors(include_url=False))\n    return item\n","sourceCodeStart":9,"sourceCodeEnd":33,"githubUrl":"https://github.com/tiangolo/fastapi/blob/3e8d1526d83a90aaf7d6eb6dc682bf150f180b25/docs_src/path_operation_advanced_configuration/tutorial007_py310.py#L9-L33","documentation":"HTTPException(422) raised when yaml.safe_load fails on the raw request body. The endpoint declares an OpenAPI requestBody of content-type application/x-yaml using Item.model_json_schema, reads the raw body manually, and attempts to parse YAML. A YAMLError becomes 'Invalid YAML'. It demonstrates handling non-JSON bodies and manually converting parser errors to HTTPExceptions.","triggerScenarios":"POST /items/ with Content-Type: application/x-yaml and a body that is not valid YAML (e.g. unbalanced indentation, bad quoting, or accidental JSON).","commonSituations":"Endpoints accepting YAML payloads; clients sending malformed YAML, wrong content-type, or UTF-8 issues. Also triggered when the body is empty or binary.","solutions":["Validate the YAML locally (e.g. yaml.safe_load in a scratch script) before sending.","Ensure the request Content-Type is application/x-yaml and the body is text YAML, not JSON.","Catch yaml.YAMLError and include line/column in the detail to help the client locate the syntax error."],"exampleFix":"// before\ntry:\n    data = yaml.safe_load(raw_body)\nexcept yaml.YAMLError:\n    raise HTTPException(status_code=422, detail=\"Invalid YAML\")\n// after (richer error)\ntry:\n    data = yaml.safe_load(raw_body)\nexcept yaml.YAMLError as e:\n    raise HTTPException(status_code=422, detail=f\"Invalid YAML: {e}\")","handlingStrategy":"try-catch","validationCode":"import yaml\nbody = 'name: foo\\ntags:\\n  - a\\n'\nyaml.safe_load(body)  # raises locally if invalid before sending","typeGuard":"def is_valid_yaml(text: str) -> bool:\n    try:\n        yaml.safe_load(text)\n        return True\n    except yaml.YAMLError:\n        return False","tryCatchPattern":"resp = requests.post('http://localhost:8000/items/', data=body, headers={'Content-Type': 'application/x-yaml'})\nif resp.status_code == 422:\n    print('Invalid YAML:', resp.json()['detail'])","preventionTips":["Lint YAML before sending.","Set Content-Type to application/x-yaml.","Include line/column info in the server's error detail."],"tags":["fastapi","http-422","yaml","request-body","validation"],"backgroundTag":null,"analyzedSha":"3e8d1526d83a90aaf7d6eb6dc682bf150f180b25","analyzedAt":"2026-08-11T02:34:52.986Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}