""" 測試 FastApi的post請求中的數據驗證, 使用的是Body 類似於Path,Query ,embed=True 請求體中使用 json key-value """ from fastapi import FastAPI, Body, Request from fastapi.responses import JSONResponse from typing import Optional from fastapi.exceptions import RequestValidationError app = FastAPI() # 創建FastApi對象 # 自定義異常處理 @app.exception_handler(RequestValidationError) # 重寫了RequestValidationError的 exception_handler方法 async def post_validation_exception_handler(request: Request, exc: RequestValidationError): """ 自定義異常處理 :param request: Request的實例化對象 :param exc: RequestValidationError的錯誤堆棧信息 :return: """ print(f'參數不對{request.method},{request.url}') return JSONResponse({'code': 400, 'msg': exc.errors()}) # post請求參數驗證 方式一: Body @app.post('/bar') async def test_post_args( post_id: int = Body(1, title='ID'), name: Optional[str] = Body(None, title='姓名', max_length=10, regex='^1'), age: Optional[int] = Body(None, title='年齡', le=96) ): """ post請求中 Body 是用來測試參數的方式之一 :param post_id: 請求參數的ID :param name: 姓名 :param age: 年齡 :return: post_id,name,age """ return {'post_id': post_id, 'name': name, 'age': age}