【6.0】Fastapi请求体参数及混合参数

发布时间 2023-10-01 15:35:31作者: Chimengmeng

【一】说明

  • 项目接上小结

【二】请求体和字段

from fastapi import APIRouter, Path, Query
from pydantic import BaseModel, Field

app03 = APIRouter()

## 请求体字段
class CityInfo(BaseModel):
    # 给 name 字段添加注解
    # ... : 表示必填字段
    # example :表示示例,,只是注解,不会被验证
    name: str = Field(..., example='Beijing')
    country: str
    country_code: str = None
    # 给 country_population 字段进行校验
    # default : 默认值
    # title : 字段标题
    # description : 字段描述
    # ge :大于等于
    country_population: int = Field(default=800, title="人口数量", description="国家人口数量", ge=800)

    # 指定配置
    class Config:
        schema_extra = {
            # 指定默认示例
            "example": {
                "name": "Shanghai",
                "country": "China",
                "country_code": "CN",
                "country_population": 1400000000
            }
        }

【三】定义视图

@app03.post('/request_body/city')
async def city_info(city: CityInfo):
    print(city.name, city.country)
    return city.dict()

【四】发起请求

image-20230929192646525

  • 携带错误的请求体参数

image-20230929192803772

  • 参数正确

image-20230929192851006

【五】多参数混合

【1】定义视图

from fastapi import APIRouter, Path, Query
from typing import List

app03 = APIRouter()

# """Request Body + Path parameters + Query parameters 多参数混合"""
@app03.put('/request_body/city/{name}')
async def mix_city_info(
        # 路径参数
        name: str,
        # 请求体 Body 可以定义多个
        city01: CityInfo,
        city02: CityInfo,
        # 对请求参数进行校验,所以使用 Query
        confirmed: int = Query(ge=0, description="确诊数", default=0),
        death: int = Query(ge=0, description="死亡数", default=0)
):
    if name == "Shanghai":
        return {"Shanghai": {"confirmed": confirmed, "death": death}}
    return city01.dict(), city02.dict()

【2】发起请求

image-20230929231650762

【六】数据格式嵌套的请求体

【1】定义视图

from datetime import date
from pydantic import BaseModel, Field
from fastapi import APIRouter, Path, Query
from typing import List

app03 = APIRouter()

## 请求体字段
class CityInfo(BaseModel):
    # 给 name 字段添加注解
    # ... : 表示必填字段
    # example :表示示例,,只是注解,不会被验证
    name: str = Field(..., example='Beijing')
    country: str
    country_code: str = None
    # 给 country_population 字段进行校验
    # default : 默认值
    # title : 字段标题
    # description : 字段描述
    # ge :大于等于
    country_population: int = Field(default=800, title="人口数量", description="国家人口数量", ge=800)

    # 指定配置
    class Config:
        schema_extra = {
            # 指定默认示例
            "example": {
                "name": "Shanghai",
                "country": "China",
                "country_code": "CN",
                "country_population": 1400000000
            }
        }

class Data(BaseModel):
    # 定义数据格式嵌套的请求体
    city: List[CityInfo] = None
    # 额外的数据类型,还有uuid datetime bytes frozenset等
    # 参考:https://fastapi.tiangolo.com/tutorial/extra-data-types/
    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)


@app03.put('/request_body/nested')
async def nested_models(data: Data):
    return data

【2】发起请求

  • 在请求体的列表类型中,可以加多个参数

image-20230929232404008