from functools import wraps
from fastapi import HTTPException, Request
from fastapi.encoders import jsonable_encoder
def validate_json_body(required_fields):
def wrapper(func):
@wraps(func)
async def wrapped(*args, **kwargs):
# 获取 FastAPI 的 Request 对象
request: Request = kwargs.get('request')
try:
# 尝试将请求体解析为 JSON
body = await request.json()
except Exception:
raise HTTPException(status_code=400, detail="Request body must be valid JSON.")
# 确保请求体是个字典
if not isinstance(body, dict):
raise HTTPException(status_code=400, detail="Request body must be a JSON object.")
# 检查必需字段是否存在且不为空
missing_fields = [field for field in required_fields if not body.get(field)]
if missing_fields:
raise HTTPException(status_code=400, detail=f"Missing or empty fields: {', '.join(missing_fields)}")
# 如果继续函数调用则验证通过
return await func(*args, **kwargs)
return wrapped
return wrapper
使用装饰器
将此装饰器应用到 FastAPI 路由中,如下所示:
python
from fastapi import FastAPI, Request
app = FastAPI()
@app.post("/create-item/")
@validate_json_body(required_fields=["name", "description"])
async def create_item(request: Request):
# 如果能执行到这一步,说明 JSON 请求体中必需字段都不为空
body = await request.json()
return {"message": "Item created successfully", "data": body}