随笔 - 134,  文章 - 0,  评论 - 0,  阅读 - 21316

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}

上面代码中把路径参数 item_id的值传递给路径函数的参数 item_id

运行代码,访问 http://127.0.0.1:8000/items/foo,返回的响应结果如下:

{"item_id" : "foo"}

声明路径参数的类型

使用python标准类型注释,声明路径操作函数中路径参数的类型。

from fastapi import FastAPI

app = FastAPI()

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

本例中将变量 item_id 的类型声明为整型 int

运行代码,访问 http://127.0.0.1:8000/items/3,返回的响应结果如下:

{"item_id": 3}

FastAPI 通过类型声明自动解析请求中的数据,使用python类型声明实现了数据校验。

如果访问URL http://127.0.0.1:8000/item/foo传入的 item_id参数值不是 int类型时,则响应报错信息如下:

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

预设路径参数

路径操作使用python的 Enum类型接收预设的路径参数。

导入 Enum并创建继承自 strEnum的子类,通过从 str继承,API文档就能把值的类型定义为字符串,然后创建包含固定值的类属性。

from enum import Enum
from fastapi import FastAPI

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"
    
app = FastAPI()

@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
    if model_name == ModelName.alexnet:
        return {"model_name": model_name, "message": "Deep Learning FTW !"}
    
    if model_name.value == "lenet":
        return {"model_name": model_name, "message": "LeCNN all the images"}
    
    return {"model_name": model_name, "message": "Have some residuals"}

访问URL http://127.0.0.1:8000/models/alexnet响应结果如下:

{
    "model_name":"alexnet",
    "message":"Deep Learning FTW !"
}

访问URL http://127.0.0.1:8000/models/lenet响应结果如下:

{
    "model_name":"lenet",
    "message":"LeCNN all the images"
}

访问URL http:127.0.0.1:8000/models/resnet响应结果如下:

{
    "model_name":"resnet",
    "message":"Have some residuals"
}

包含路径的路径参数

假设路径操作的路径为 /file/{file_path},但是需要 file_path中包含路径,比如, home/johndoe/myfile.txt,此时的文件URL是这样的: /files/home/johndoe/myfile.txt

直接使用Starlette的选项声明包含路径的路径参数:/files/{file_path: path}

from fastapi import FastAPI

app = FastAPI()

@app.get("/files/{file_path: path}")
async def read_file(file_path: str):
    return {"file_path": file_path}

注意:

包含 /home/johndoe/myfile.txt的路径参数要以斜杠开头。

本例中的URL是 /files/home/johndoe/myfile.txt fileshome 之间要使用双斜杠 //

FastAPI 查询参数

声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数。

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的 之后,以&分隔。

上面运行后访问的URL为: http:/127.0.0.1:8000/items/?skip=0&limit=10

访问结果为:

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

默认值

上面代码中 skip=0limit=10设定为默认值。

如果访问: http:127.0.0.1:8000/items/?skip=20skip=20为在URL中设定的值,这时limit=10,表示默认值为10.

可选参数

from fastapi import FastAPI

from typing import Optional

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

本例中,查询参数 q 是可选的,默认值为None。

查询参数类型转换

参数还可以声明为bool类型,FastAPI会自动转换参数类型:

from typing import Optional
from fastapi import FastAPI

app = FastAIP()

@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):
    item = {"item_id": item_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item

访问URL http://127.0.0.1:8000/items/foo?short=1的结果如下:

{
    "item_id":"foo"
}

访问URL http://127.0.0.1:8000/items/foo?short=True的结果如下:

{
    "item_id":"foo"
}

访问URL http://127.0.0.1:8000/items/foo?short=true的结果如下:

{
    "item_id":"foo"
}

访问URL http://127.0.0.1:8000/items/foo?short=false的结果如下:

{
    "item_id":"foo","description":"This is an amazing item that has a long description"
}

访问URL http://127.0.0.1:8000/items/foo?short=False 的结果如下:

{
    "item_id":"foo","description":"This is an amazing item that has a long description"
}

访问URL http://127.0.0.1:8000/items/foo的结果如下:

{
    "item_id":"foo","description":"This is an amazing item that has a long description"
}

多个路径参数和查询参数

FastAPI可以识别同时声明的多个路径参数和查询参数,而且声明查询参数的顺序并不重要。

from typing import Optional
from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(user_id: int, item_id: str, q: Optional[str] = None, short: bool = False):
    item = {"item_id": item_id, "owner_id": user_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update({"description": "This is an amazing item that has a long description"})
        
    return item

必选查询参数

如果要把查询参数设置为必选,就不要声明默认值:

from fastapi import FastAPI

app = FastAPI()

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

这里的查询参数 needy的类型为 str的必选查询参数。

访问URL http://127.0.0.1:8000/items/foo-item时报错,报错信息如下:

{
    "detail": [
        {
            "loc": [
                "query",
                "needy"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

访问URL http://127.0.0.1:8000/items/foo-item?needy=soomneedy的结果如下:

{
    "item_id": "foo-item",
    "needy": "sooooneedy"
}

当然,把一些参数定义为必选,另一些参数设置为默认值,再把其他参数定义为可选,这些操作都是可以的。

from typing import Optional

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_user_item(
    item_id: str, needy: str, skip: int = 0, limit: Optional[int] = None
):
    item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return item

上面代码中参数分别是:

  • needy 为必选参数
  • skip为默认值参数,默认值为0
  • limit为可选参数
posted on   Steam残酷  阅读(548)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示