【FastAPI】 GET 方法

路径参数

比如访问:127.0.0.1/user/123/

from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/user/{id}/")
async def main(id: int):
    return {"id":id}

if __name__ == '__main__':
    uvicorn.run(
        app = app,
        host = "127.0.0.1",
        port = 80,
    )

API文档地址:http://127.0.0.1/docs
mark

固定的路径参数

@app.get("/user/id/")
async def main():
    return {"id": "the current user"}

@app.get("/user/{id}/")
async def main(id: int):
    return {"id":id}

mark

预留路径值

传入的路径参数 只能在预留路径里,不然就报错

from fastapi import FastAPI
# 导入枚举类
from enum import Enum
import uvicorn

# 预留路径类  继承 str,文档将能够知道这些值的类型
class ModelName(str, Enum):
    # 预留的路径
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

app = FastAPI()

@app.get("/model/{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"}

if __name__ == '__main__':
    uvicorn.run(
        app = app,
        host = "127.0.0.1",
        port = 80,
    )

mark

路径转换器

访问 /files/bigdataboy/a.txtfile_path将能得到 bigdataboy/a.txt

# 添加上 :path 即可
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}

mark

查询参数

查询参数是指 ?后面的 & 分割的键值对

http://127.0.0.1:8000/items/?skip=0&limit=2

from fastapi import FastAPI
import uvicorn

app = FastAPI()

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

@app.get("/items/")
# 设置的默认值,当默认值是 None 时,表示该值为可选
async def read_item(skip: int = 0, limit: int = 2, default: str =None): 
    # 一个列表切片
    return fake_items_db[skip : skip + limit]

if __name__ == '__main__':
    uvicorn.run(
        app = app,
        host = "127.0.0.1",
        port = 80,
    )

mark

注意

如果声明可选时出现以下类似错误

# 声明可选
limit: int = None

# 出现以下类似错误
Incompatible types in assignment (expression has type "None", variable has type "int")

这是你需要这样做

from typing import Optional

limit: Optional[int] = None

完整实例

from fastapi import FastAPI
from typing import Optional
import uvicorn

app = FastAPI()

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

if __name__ == '__main__':
    uvicorn.run(
        app = app,
        host = "127.0.0.1",
        port = 80,
    )

mark

发表评论 / Comment

用心评论~