Skip to content

FastAPI

建议直接看官网学习,最快最直接的入门方式。
FastAPI的官网: https://fastapi.org.cn/

FastAPI 是一个现代、快速(高性能)的 Web 框架,用于使用基于标准 Python 类型提示的 Python 构建 API。

1. FastAPI项目的启动方式

方式一: 点击PyCharm右上角的运行按钮
方式二: 在终端中运行命令 uvicorn main:app --reload

--reload: 自动重载,代码修改后自动重启服务。

2. FastAPI会自动生成两个文档

http://127.0.0.1:8000/docs 集成了 Swagger UI
http://127.0.0.1:8000/redoc 使用 ReDoc

3. 路由传参

1. 路径参数

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

2. 查询参数

设置查询参数并设置默认值

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

可选参数: 将默认值设置为None

注意,FastAPI 足够智能,可以识别出 item_id 是路径参数,而 q 不是,因此 q 是一个查询参数。

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