FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 APIs,基于 Python 3.7+ 的类型提示。FastAPI 是一个非常流行的选择,因为它提供了很多现代 Web 开发所需的功能,同时保持了简洁性和易用性。

FastAPI 的特点

  1. 声明式路由

    • 使用装饰器来定义 API 路由,使代码更加清晰和易于维护。
  2. 自动文档生成

    • 自动生成交互式文档(支持 Swagger UI 和 ReDoc),方便测试和文档编写。
  3. 异步支持

    • 支持异步请求处理,利用 Python 的 async/await 语法提高性能。
  4. 类型提示

    • 利用 Python 的类型提示来自动验证请求和响应数据。
  5. 依赖注入

    • 强大的依赖注入系统,简化了服务和组件的管理和注入。
  6. 性能

    • 快速响应时间和高吞吐量,适合构建高性能的 API。

安装 FastAPI

要开始使用 FastAPI,首先需要安装它。你可以通过 pip 来安装 FastAPI:

1
pip install fastapi

此外,你还需要安装一个 ASGI 兼容的服务器,如 uvicorn,用于运行 FastAPI 应用:

1
pip install uvicorn

快速入门示例

下面是一个简单的 FastAPI 应用示例:

  1. 创建一个 FastAPI 应用
1
2
3
4
5
6
7
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
return {"message": "Hello, FastAPI!"}
  1. 运行 FastAPI 应用

你可以使用 uvicorn 来运行你的 FastAPI 应用:

1
uvicorn main:app --reload

这里的 main 是包含 FastAPI 应用的 Python 文件名(假设为 main.py)。--reload 参数使服务器在代码更改时自动重启。

  1. 访问应用

启动服务器后,你可以通过浏览器或 HTTP 客户端访问 http://127.0.0.1:8000 来查看你的应用。

  1. 查看文档

FastAPI 自动生成交互式文档。你可以通过访问 http://127.0.0.1:8000/docshttp://127.0.0.1:8000/redoc 来查看和测试你的 API。

接口发布demo

FastAPI 提供了许多其他功能,包括:

路径参数

  • 用于提取 URL 中的路径参数。
1
2
3
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}

查询参数

  • 用于提取 URL 查询字符串中的参数。
1
2
3
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}

请求体 json

  • 用于处理 POST 请求中的 JSON 数据。
1
2
3
4
5
6
7
8
9
10
11
from pydantic import BaseModel

class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None

@app.post("/items/")
async def create_item(item: Item):
return item

表单数据

1
2
3
4
5
6
7
from fastapi import FastAPI, Form

app = FastAPI()

@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username, "password": password}

文件上传

create_file 接口接受原始字节数据,而 create_upload_file 接口接受上传文件对象。

1
2
3
4
5
6
7
8
9
10
11
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/files/")
async def create_file(file: bytes = File(...)):
return {"file_size": len(file)}

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}

依赖注入

  • 用于管理服务的依赖关系。
  • 定义一个依赖项来处理请求的解析
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from fastapi import FastAPI, Depends

app = FastAPI()

async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(params: dict = Depends(common_parameters)):
return params

@app.get("/users/")
async def read_users(params: dict = Depends(common_parameters)):
return params

使用 Request 对象

访问原始的请求对象,例如处理复杂的请求头或原始请求数据。

read_headers 接口读取请求头,read_raw_body 接口读取原始请求体。

1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/headers/")
async def read_headers(request: Request):
headers = request.headers
return {"headers": headers}

@app.post("/raw-body/")
async def read_raw_body(request: Request):
body = await request.body()
return {"body": body.decode()}

返回值

使用pydantic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class PathInfo(BaseModel):
path: str
additional_info: str | None = None

class ResponseModel(BaseModel):
paths: dict[str, PathInfo]

@app.get("/paths/", response_model=ResponseModel)
async def get_paths():
path_data = {
"id1": PathInfo(path="path1", additional_info="info1"),
"id2": PathInfo(path="path2", additional_info="info2"),
"id3": PathInfo(path="path3"),
# ...
}
response = ResponseModel(paths=path_data)
return response

纯字典

1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi import FastAPI

app = FastAPI()

@app.get("/paths/")
async def get_paths():
paths = {
"id1": "path1",
"id2": "path2",
"id3": "path3",
# ...
}
return paths

总结

FastAPI 是一个强大且灵活的 Web 框架,非常适合用于构建高性能的 API。通过上述示例,你应该能够快速上手并开始构建自己的 FastAPI 应用。如果你需要更深入的学习或具体的案例,可以查阅 FastAPI 的官方文档或其他资源。

服务生成的所有内容均由人工智能模型生成,其生成内容的准确性和完整性无法保证,不代表我们的态度或观点