FastAPI系列(06):请求信息之查询参数
本系列汇总,请查看这里:https://www.cnblogs.com/uncleyong/p/19503695
查询参数
官网:https://fastapi.tiangolo.com/tutorial/query-params/
定义
路径函数中声明不属于路径参数的其他函数参数,它们将被自动解释为"查询字符串"参数,就是 url? 之后用`&`分割的 key-value 键值对;
也就是说,单一类型的参数(例如int、float、str、bool等),且在路径中未声明,它将被解释为 query 参数;
有默认值即可选,否则必选。
示例


演示代码:Keywords,ViewCount,DiggCount均为查询参数
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/blogs")
def get_blogs(Keywords,ViewCount,DiggCount):
return {"Keywords": Keywords,
"ViewCount":ViewCount,
"DiggCount":DiggCount
}
if __name__ == '__main__':
uvicorn.run("query_parameter:app", port=8001, reload=True)
接口文档中,参数必填,类型是any,query表示是查询参数

通过下面Curl可以看到,请求后,参数放路径中?后面

路径参数和查询参数同时存在
Keywords是路径参数,ViewCount,DiggCount是查询参数
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/blogs/{Keywords}")
def get_blogs(Keywords,ViewCount,DiggCount):
return {"Keywords": Keywords,
"ViewCount":ViewCount,
"DiggCount":DiggCount
}
if __name__ == '__main__':
uvicorn.run("query_parameter:app", port=8001, reload=True)
第一个参数是path,后面两个是query

第一个参数在路径中,后面两个参数在?后面

场景:路径参数必填,查询参数非必填
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/blogs/{Keywords}")
def get_blogs(Keywords:str,ViewCount=0,DiggCount=None):
return {"Keywords": Keywords,
"ViewCount":ViewCount,
"DiggCount":DiggCount
}
if __name__ == '__main__':
uvicorn.run("query_parameter:app", port=8001, reload=True)
没有默认值的查询参数都是必填;路径参数不能设置默认值

Keywords输入“全栈测试笔记”后发送请求
请求只发送了两个参数,当 FastAPI 接口的返回数据中包含 None 时,FastAPI 会自动将其序列化为 JSON 格式的 null,因为 JSON 不支持 None,只能用 null 表示空值

参数类型声明
如果是Python 3.9+,多类型用|分割,更简洁;否则,使用 Union[str, None] 标注,等价于Optional[str](兼容 Python 3.9 以下版本)
示例
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/blogs/{Keywords}")
# |是Python 3.9+ 推荐,更简洁
def get_blogs(Keywords:str,ViewCount:int,DiggCount:int|None=100): # 注意:带默认值的参数不能位于不带默认值参数的前面
return {"Keywords": Keywords,
"ViewCount":ViewCount,
"DiggCount":DiggCount
}
if __name__ == '__main__':
uvicorn.run("query_parameter:app", port=8001, reload=True)
访问接口文档

填入参数

响应

__EOF__
本文作者:持之以恒(韧)
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!

浙公网安备 33010602011771号