Fastapi之请求体

1.表单格式

from fastapi import Form


app = FastAPI()


@app.post('/login')
def user_login(username: str = Form(...), password: str = Form(...)):
    """pip install python-multipart"""
    return {"username": username, "password": password}

2.json格式

class CityInfo(BaseModel):
    name: str = Field(..., example="Beijing")
    country: str
    country_code: Optional[str] = None
    country_population: int = Field(default=800, title="人口数量", description="国家的人口数量", ge=800)

    class Config:
        schema_extra = {
            "example": {  # 响应示例
                "name": "Shanghai",
                "country": "China",
                "country_code": "CN",
                "country_population": 140000000
            }
        }

@users.post("/add-city")
def city_info(city: CityInfo):
    print(city.country)
    return city

3.嵌套格式

class CityInfo(BaseModel):
    name: str = Field(..., example="Beijing")
    country: str
    country_code: Optional[str] = None
    country_population: int = Field(default=800, title="人口数量", description="国家的人口数量", ge=800)

    class Config:
        schema_extra = {
            "example": {
                "name": "Shanghai",
                "country": "China",
                "country_code": "CN",
                "country_population": 140000000
            }
        }


class Data(BaseModel):
    city: List[CityInfo] = None
    date: date
    confirmed: int = Field(ge=0, description="确诊数", default=0)
    deaths: int = Field(ge=0, description="死亡数", default=0)
    recovered: int = Field(ge=0, description="痊愈数", default=0)

@users.put("request_body/nested")
def nested_models(data: Data):
    return data
posted @ 2022-06-23 14:07  fatpuffer  阅读(87)  评论(0编辑  收藏  举报