上一篇寫的 GET 請求接口,這節課寫 POST 請求,GET 請求沒有請求體,POST 有請求體。
需求:POST 請求實現登錄,入參有賬號、密碼兩個參數,請求方式為 JSON 格式
# -*- coding:utf-8 -*-
"""
測試 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
import uvicorn
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(
name: Optional[str] = Body(None, title='用戶名', max_length=10),
pwd: Optional[str] = Body(None, title='密碼', max_length=10),
):
"""
post請求中 Body 用來傳遞參數
:param name: 用戶
:param pwd: 密碼
:return: name, pwd
"""
return {'name': name, 'pwd': pwd}
if __name__ == '__main__':
uvicorn.run(app='demo002:app', host="127.0.0.1", port=8000, reload=True, debug=True)
運行腳本后,使用 PostMan 來調試一下。
接口的響應還比較簡單,入參是什么,接口返回什么,后續優化接口的響應,
比如加入狀態碼等。