![image-20220826232100824](https://img-blog.csdnimg.cn/img_convert/8522dd84dfbf16c0ed345495d3aad835.png)
总代码
先上总代码,导入相关依赖包即可正常编译运行
from fastapi import FastAPI, Path, Query, Cookie, Header
from enum import Enum #导入枚举类型
from typing import Optional, List
from pydantic import BaseModel, Field
from datetime import date
import uvicorn
test = FastAPI()
@test.get("/path/canshu")
def path_01():
'''路径参数和数字验证'''
return {"message":"This is a message"}
@test.get("/path/{canshu}")
def path_01(canshu):
return {"message": canshu}
class CityName(str, Enum):
Beijing = 'Slaine'
Shanghai = 'Troyard'
@test.get("/enum/{city}")
async def latest(city: CityName):
if city == CityName.Beijing:
return {"city_name":city, "confirmed": 1492, "death": 9}
if city == CityName.Shanghai:
return {"city_name": city, "confirmed": 1550, "death": 29}
return {"city_name":city, "latest": "unknown"}
@test.get("/file/{file_path:path}")
def filepath(file_path: str):
'''默认都可传递\路径,有无:path直接区别能否传递/的路径'''
return f"The file path is {file_path}"
'''长度和正则表达式的验证,最频繁且实用的接口规则'''
@test.get("/path_wm/{num}")
def path_jy( #下面...同None
num : int = Path(..., title="Exanple", description="无描述", ge=1,le=10)
):
return num
@test.get("/query")
def page_limit(page: int=1, limit: Optional[int] = None):#这里的page和limit查询两参数都已有默认值
'''查询参数和字符串验证'''
if limit: #如果存在limit值传入
return {"page":page, "limit":limit}
return {"page":page}
@test.get("/query/bool/con")
def type_con(param: bool = False): #
'''查询参数设定默认值为Flase'''
return param
@test.get("/query/va")
def query_pa(
value: str = Query(..., min_length=3, max_length=6, regex="^a"), #请求参数的字符长度和起始限制
values: List[str] = Query(default=["v1", "v2"], alias="这是起的别名") #队列形式添加字符串和别名
):
return value, values
'''请求体和字段'''
class CityInfo(BaseModel):
name: str = Field(..., example = "SlainWWWe")
country: str
country_code: str = None
country_population: int=Field(default=800, title="人口数量", description="国家人口数量" ,ge=500)#最小值为500
class Config:
schema_extra = {
"example" : { #这里注意是 example 关键词,才能让以下字段设为默认字段
"name": "Shanghai",
"country": "ChinaMMM",
"country_code": "CN",
"country_population": 1400000000,
}
}
@test.post("/request_body/city")
def city_info(city: CityInfo):
'''请求体和字段'''
print(city.name, city.country)
return city.dict()
'''查询参数、路径参数、请求体 多参数混合使用'''
@test.put("/request_body/city/{name}")
def mix_city(
name: str, #路径参数
city01: CityInfo,#请求体body
city02: CityInfo,#同上
confirmed: int = Query(ge=0, description="确诊数量", default=0), #查询参数
death: int = Query(ge=0, description="死亡数量", default=0),#同上
):
if name == "Slaine":
return {"Slaine": {"confirmed": confirmed, "death":death}}
return city01.dict(), city02.dict()
'''数据格式嵌套的请求体'''
class Data(BaseModel):
city: List[CityInfo] = None #定义数据格式嵌套的请求体,且因为是List列表形式所以可用传入多组city
date: date #直接使用datatime包中的date
# 使用pydantic定义请求体数据时候要对字段进行校验,一般用Field类校验
#使用路径参数时候对数据进行Path类校验,对查询参数进行校验使用Query类
confirmed: int = Field(ge=0, description="确诊数量", default=0)
death: int = Field(ge=0, description="死亡数量", default=0)
recovered: int = Field(ge=0, description="痊愈数目", default=0)
@test.put("/request_body/nested")
def nested_models(data: Data):
return data
'''Cookie 和 Header参数'''
@test.get("/cookie")
def cookie(cookie_id: Optional[str] = Cookie(None)): #这里的Cookie(None)就是对 cookie类型默认值 的设置,若没有Cookie(),即为设定cookie_id的查询参数
return {"cookie_id": cookie_id}
@test.get("/header") #这里的Header()同上,convert_underscores=True是自动将下划线 _ 转换为 - (有的情况下下划线会报错)
def header(user_agent: Optional[str] = Header(None, convert_underscores=True), x_token: List[str] = Header(None)):
return {"user_agent":user_agent, "x_token": x_token}
#user_agent即使不设置值也会返回当前浏览器参数值
if __name__ =='__main__':
uvicorn.run(test, host='127.0.0.1', port=8009)
在运行端口的/docs目录下有自带测试接口的界面
路径参数接口
@test.get("/path/canshu")
def path_01():
'''路径参数和数字验证'''
return {"message":"This is a message"}
@test.get("/path/{canshu}")
def path_01(canshu):
return {"message": canshu}
url请求和响应
![image-20220825234715109](https://img-blog.csdnimg.cn/img_convert/c96e6b19b90c662b5511977f83761cc7.png)
url请求和响应
![image-20220825234808374](https://img-blog.csdnimg.cn/img_convert/a8358bc9e1971330f60d9f3e0d97a4ea.png)
因为是GET传参,也可以用url请求测试
定义类中待选属性的接口传参
class CityName(str, Enum):
Beijing = 'Slaine'
Shanghai = 'Troyard'
@test.get("/enum/{city}")
async def latest(city: CityName):
if city == CityName.Beijing:
return {"city_name":city, "confirmed": 1492, "death": 9}
if city == CityName.Shanghai:
return {"city_name": city, "confirmed": 1550, "death": 29}
return {"city_name":city, "latest": "unknown"}
![image-20220825235123358](https://img-blog.csdnimg.cn/img_convert/a04735f13985e955dfe5e09f2e63b847.png)
利用:path
允许/ \ 的路径传参接口
@test.get("/file/{file_path:path}")
def filepath(file_path: str):
'''默认都可传递\路径,有无:path直接区别能否传递/的路径'''
return f"The file path is {file_path}"
![image-20220825235312487](https://img-blog.csdnimg.cn/img_convert/d0e3533b93ef176fcbb6dd84542c5130.png)
对输入字符限制的传参接口
'''长度和正则表达式的验证,最频繁且实用的接口规则'''
@test.get("/path_wm/{num}")
def path_jy( #下面...同None
num : int = Path(..., title="Exanple", description="无描述", ge=1,le=10)
):
return num
![image-20220825235407422](https://img-blog.csdnimg.cn/img_convert/2b9b944b6ad606c41af0949d0dd26f60.png)
为page和limit变量传入对应的参数
@test.get("/query")
def page_limit(page: int=1, limit: Optional[int] = None):#这里的page和limit查询两参数都已有默认值
'''查询参数和字符串验证'''
if limit: #如果存在limit值传入
return {"page":page, "limit":limit}
return {"page":page}
传入布尔值参数并返回
@test.get("/query/bool/con")
def type_con(param: bool = False): #
'''查询参数设定默认值为Flase'''
return param
对传入字符串长度和开头限制的别名接口;队列形式添加字符串和别名
@test.get("/query/va")
def query_pa(
value: str = Query(..., min_length=3, max_length=6, regex="^a"), #请求参数的字符长度和起始限制
values: List[str] = Query(default=["v1", "v2"], alias="这是起的别名") #队列形式添加字符串和别名
):
return value, values
![image-20220826001818168](https://img-blog.csdnimg.cn/img_convert/fabce7a22852e5537144103f22f2a667.png)
POST传入类中属性参数接口
'''请求体和字段'''
class CityInfo(BaseModel):
name: str = Field(..., example = "SlainWWWe")
country: str
country_code: str = None
country_population: int=Field(default=800, title="人口数量", description="国家人口数量" ,ge=500)#最小值为500
class Config:
schema_extra = {
"example" : { #这里注意是 example 关键词,才能让以下字段设为默认字段
"name": "Shanghai",
"country": "ChinaMMM",
"country_code": "CN",
"country_population": 1400000000,
}
}
@test.post("/request_body/city")
def city_info(city: CityInfo):
'''请求体和字段'''
print(city.name, city.country)
return city.dict()
![image-20220826225111226](https://img-blog.csdnimg.cn/img_convert/c4b1d647aba6ef7bc0eb028803b754fc.png)
查询参数、路径参数、请求体 多参数混合使用
'''查询参数、路径参数、请求体 多参数混合使用'''
@test.put("/request_body/city/{name}")
def mix_city(
name: str, #路径参数
city01: CityInfo,#请求体body
city02: CityInfo,#同上
confirmed: int = Query(ge=0, description="确诊数量", default=0), #查询参数
death: int = Query(ge=0, description="死亡数量", default=0),#同上
):
if name == "Slaine":
return {"Slaine": {"confirmed": confirmed, "death":death}}
return city01.dict(), city02.dict()
![image-20220826225418566](https://img-blog.csdnimg.cn/img_convert/3e39142184d50a5543a6a16eed67dd84.png)
数据格式嵌套的请求体接口
'''数据格式嵌套的请求体'''
class Data(BaseModel):
city: List[CityInfo] = None #定义数据格式嵌套的请求体,且因为是List列表形式所以可用传入多组city
date: date #直接使用datatime包中的date
# 使用pydantic定义请求体数据时候要对字段进行校验,一般用Field类校验
#使用路径参数时候对数据进行Path类校验,对查询参数进行校验使用Query类
confirmed: int = Field(ge=0, description="确诊数量", default=0)
death: int = Field(ge=0, description="死亡数量", default=0)
recovered: int = Field(ge=0, description="痊愈数目", default=0)
@test.put("/request_body/nested")
def nested_models(data: Data):
return data
![image-20220826230850971](https://img-blog.csdnimg.cn/img_convert/d73ff2120578029b71cf0da37c436d02.png)
Cookie 和 Header参数传入接口
'''Cookie 和 Header参数'''
@test.get("/cookie")
def cookie(cookie_id: Optional[str] = Cookie(None)): #这里的Cookie(None)就是对 cookie类型默认值 的设置,若没有Cookie(),即为设定cookie_id的查询参数
return {"cookie_id": cookie_id}
@test.get("/header") #这里的Header()同上,convert_underscores=True是自动将下划线 _ 转换为 - (有的情况下下划线会报错)
def header(user_agent: Optional[str] = Header(None, convert_underscores=True), x_token: List[str] = Header(None)):
return {"user_agent":user_agent, "x_token": x_token}#user_agent即使不设置值也会返回当前浏览器参数值
![image-20220826231857908](https://img-blog.csdnimg.cn/img_convert/3ba28d756c1d82e27a7828c3accaf8d2.png)