| 1 |
import yaml |
| 2 |
from fastapi import FastAPI, HTTPException, Request |
| 3 |
from pydantic import BaseModel, ValidationError |
| 4 |
|
| 5 |
app = FastAPI() |
| 6 |
|
| 7 |
|
| 8 |
class Item(BaseModel): |
| 9 |
name: str |
| 10 |
tags: list[str] |
| 11 |
|
| 12 |
|
| 13 |
@app.post( |
| 14 |
"/items/", |
| 15 |
openapi_extra={ |
| 16 |
"requestBody": { |
| 17 |
"content": {"application/x-yaml": {"schema": Item.model_json_schema()}}, |
| 18 |
"required": True, |
| 19 |
}, |
| 20 |
}, |
| 21 |
) |
| 22 |
async def create_item(request: Request): |
| 23 |
raw_body = await request.body() |
| 24 |
try: |
| 25 |
data = yaml.safe_load(raw_body) |
| 26 |
except yaml.YAMLError: |
| 27 |
raise HTTPException(status_code=422, detail="Invalid YAML") |
| 28 |
try: |
| 29 |
item = Item.model_validate(data) |
| 30 |
except ValidationError as e: |
| 31 |
raise HTTPException(status_code=422, detail=e.errors(include_url=False)) |
| 32 |
return item |