前面讲述了FastApi的搭建与运行,这篇来讲下FastApi的路径参数与查询参数。

路径参数

可以使用与Python格式字符串相同的语法来声明路径参数

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id):
    return {"item_id": item_id}

上面代码,path参数item_id的值将作为参数传递给read_item函数

在浏览器中运行一下

可以看到,path为 /items/foo,其中的foo将作为实参传入read_item函数

是不是觉得很简单呢?

Query参数

声明不属于路径参数的其他功能参数时,它们将自动解释为Query参数

from fastapi import FastAPI

app = FastAPI()

@app.get("/items")
async def read_item(uid):
    return {"uid": uid}

来看上面简单例子,这个例子中,没有路径参数,但却有其他的参数uid,这个uid就将解释为Query参数。

Query是在path后面加上?形参名=值,如果有多个查询参数以&字符分隔,比如path?参数名=值&参数名=值,其中的值将被作为实参传入函数。

在上例中转化的URL为:

http://127.0.0.1:8000/items?uid=1

 在来看一个多个查询参数的例子

from fastapi import FastAPI

app = FastAPI()

@app.get("/items")
async def read_item(uid, aid):
    return {"uid": uid, "aid": aid}

上例中转化的URL为:

http://127.0.0.1:8000/items?uid=1&aid=2

 参数类型

上面几个简单例子,细心一点就会发现,参数的类型可以随便定义,这样可能就会因为用户的随便传入值而报错,比如uid需要的是int类型,用户传了个str类型过来,这时怎么办呢?有没有简单的方式呢?

在FastApi中很方便的帮我们实现了这个功能。

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{uid}")
async def read_item(uid: int, name: str):
    return {"uid": uid, "name": name}

上面例子中,即含有路径参数也含有Query参数,且路径参数必须为int类型,name必须为str类型,用户必须传指定类型才可以访问成功。

http://127.0.0.1:8000/items/1?name=apple

上面URL访问成功,当用户传入别的类型时就会给出提示信息,比如访问下面连接

http://127.0.0.1:8000/items/hello?name=apple

上面连接的路径参数传了一个str类型,服务器就会给出提示

{
    "detail": [{
        "loc": ["path", "uid"],
        "msg": "value is not a valid integer",
        "type": "type_error.integer"
    }]
}

给出了具体信息,说uid参数的值不是int类型,是不是很方便。 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐