from pydantic import BaseModel, Field
from fastapi import APIRouter, Path, Query, HTTPException
from fastapi.responses import HTMLResponse
def err_description(code:int):
match code:
case 404:
return {"description": "404 Not found"}
case 402:
return {"description": "402 Not found"}
__:
return {"description": "unknow Not found"}
router = APIRouter(
tags=["test"],
prefix="/test",
responses={404: err_description(404), 402:err_description(402)}
)
class PostParams(BaseModel):
param1: str = Field("", title="请求的第一个参数")
param2: int = Field(0, title="请求的第二个参数")
class PostParamsRes(BaseModel):
param1: str = Field("", title="响应的第一个参数")
param2: int = Field("", title="响应的第二个参数")
@router.post("/post/{path_param}", description="post 请求模板", response_model=PostParams)
async def post(path_param: str = Path(), post_param: PostParams = PostParams()):
try:
res = post_param.dict()
res.update({"path_param": path_param})
return res
except Exception as e:
raise HTTPException(402, detail="请求失败")
@router.get("/get/{path_param}", description="get 请求模板", response_model=PostParams)
async def get(path_param: str = Path(), param1: str = "get", param2: int = 0):
try:
return PostParams(param1=param1, param2=param2)
except Exception as e:
raise HTTPException(402, detail="请求失败")