fastapi(三)查询参数

本文深入探讨了FastAPI框架中如何使用查询参数,包括必填、可选参数的定义方式,以及如何处理多个路径和查询参数。同时,文章还讲解了如何通过Optional类型注解来正确处理可选参数。

当你声明函数参数的时候,如果参数并不是来自路径参数中,那么将被自动视为查询参数。

from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

这个查询是一个键值对,在url中的?之后,并且使用&符号隔开。

http://127.0.0.1:8000/items/?skip=0&limit=10
可选参数
当你把查询参数默认值设置为None的时候,这个参数就是可选参数。

async def read_item(item_id: str, q: str = None):

多路径参数和查询参数

@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: str = None, short: bool = False
):

必须的查询参数
如果查询参数为必须的,可以在声明的时候不添加默认值

@app.get("/items/{item_id}")
async def read_user_item(item_id: str, needy: str):

warnning:
如果在声明参数为可选参数的时候,程序报错,
limit:str=None
Incompatible types in assignment (expression has type “None”, variable has type “int”)
可以使用Optional告诉程序变量的值可以为None
from typing import Optional

async def read_user_item(item_id:str,limit:Optional[int]=None):

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值