tiangolo/fastapi · error · HTTPException

Invalid YAML

Error message

Invalid YAML

What it means

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.

Solutions

  1. Validate the YAML locally (e.g. yaml.safe_load in a scratch script) before sending.
  2. Ensure the request Content-Type is application/x-yaml and the body is text YAML, not JSON.
  3. Catch yaml.YAMLError and include line/column in the detail to help the client locate the syntax error.

Example fix

// before
try:
    data = yaml.safe_load(raw_body)
except yaml.YAMLError:
    raise HTTPException(status_code=422, detail="Invalid YAML")
// after (richer error)
try:
    data = yaml.safe_load(raw_body)
except yaml.YAMLError as e:
    raise HTTPException(status_code=422, detail=f"Invalid YAML: {e}")
Defensive patterns

Strategy: try-catch

Validate before calling

import yaml
body = 'name: foo\ntags:\n  - a\n'
yaml.safe_load(body)  # raises locally if invalid before sending

Type guard

def is_valid_yaml(text: str) -> bool:
    try:
        yaml.safe_load(text)
        return True
    except yaml.YAMLError:
        return False

Try / catch

resp = requests.post('http://localhost:8000/items/', data=body, headers={'Content-Type': 'application/x-yaml'})
if resp.status_code == 422:
    print('Invalid YAML:', resp.json()['detail'])

Prevention

When it happens

Trigger: 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).

Common situations: Endpoints accepting YAML payloads; clients sending malformed YAML, wrong content-type, or UTF-8 issues. Also triggered when the body is empty or binary.

Related errors


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

Appendix: source

Thrown at docs_src/path_operation_advanced_configuration/tutorial007_py310.py:27

    name: str
    tags: list[str]


@app.post(
    "/items/",
    openapi_extra={
        "requestBody": {
            "content": {"application/x-yaml": {"schema": Item.model_json_schema()}},
            "required": True,
        },
    },
)
async def create_item(request: Request):
    raw_body = await request.body()
    try:
        data = yaml.safe_load(raw_body)
    except yaml.YAMLError:
        raise HTTPException(status_code=422, detail="Invalid YAML")
    try:
        item = Item.model_validate(data)
    except ValidationError as e:
        raise HTTPException(status_code=422, detail=e.errors(include_url=False))
    return item

View on GitHub (pinned to 3e8d1526d8)