ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 主要特点
  • 安装
  • 基本示例
  • 路径参数
  • 查询参数
  • 请求体
  • 响应模型
  • 表单数据
  • 文件上传
  • 异常处理
  • 中间件
  • 依赖注入
  • 安全性
  • 优势总结

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

主要特点 #

  1. 快速:与 NodeJS 和 Go 相当的高性能
  2. 快速编码:提高开发速度约 200%-300%
  3. 更少错误:减少约 40% 的人为错误
  4. 直观:强大的编辑器支持
  5. 简单:易于使用和学习
  6. 简短:最小化代码重复
  7. 健壮:生产就绪的代码
  8. 标准化:基于(并完全兼容)API 开放标准

安装 #

pip install fastapi
pip install uvicorn[standard]  # 用于运行 FastAPI 的 ASGI 服务器

基本示例 #

# 导入 FastAPI 类
from fastapi import FastAPI
# 创建 FastAPI 应用实例
app = FastAPI()

# 定义根路径的 GET 请求接口
@app.get("/")
# 处理根路径请求的函数
# 返回一个字典,内容为{"Hello": "World"}
def read_root():
    return {"Hello": "World"}

# 定义带有路径参数的 GET 请求接口
@app.get("/items/{item_id}")
# 处理带参数请求的函数,item_id 为路径参数,q 为可选查询参数
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

# 仅在直接运行本文件时启动 uvicorn 服务器
if __name__ == "__main__":
    # 导入 uvicorn 服务器
    import uvicorn
    # 启动应用,host 为 127.0.0.1,端口为 8000,自动重载
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

路径参数 #

# 导入 FastAPI 类
from fastapi import FastAPI
# 创建 FastAPI 应用实例
app = FastAPI()

# 定义带有路径参数的 GET 请求接口
@app.get("/items/{item_id}")
# 处理带参数请求的函数,item_id 为路径参数
def read_item(item_id: int):
    return {"item_id": item_id}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

查询参数 #

# 导入 FastAPI 类
from fastapi import FastAPI
# 创建 FastAPI 应用实例
app = FastAPI()

# 定义带有查询参数的 GET 请求接口
@app.get("/items/")
# 处理带查询参数请求的函数,skip 和 limit 为查询参数
def read_items(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

请求体 #

# 导入 FastAPI 和 Pydantic 的 BaseModel
from fastapi import FastAPI
from pydantic import BaseModel

# 定义请求体的数据模型
class Item(BaseModel):
    # 名称,字符串类型
    name: str
    # 描述,字符串类型,可选
    description: str = None
    # 价格,浮点数类型
    price: float
    # 税,浮点数类型,可选
    tax: float = None

# 创建 FastAPI 应用实例
app = FastAPI()

# 定义 POST 请求接口,接收 Item 类型的请求体
@app.post("/items/")
def create_item(item: Item):
    return item

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

响应模型 #

# 导入 FastAPI 和 Pydantic 的 BaseModel
from fastapi import FastAPI
from pydantic import BaseModel

# 定义响应模型
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

app = FastAPI()

# 指定 response_model,返回的数据会自动校验和序列化
@app.post("/items/", response_model=Item)
def create_item(item: Item):
    return item

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

表单数据 #

# 导入 FastAPI 和 Form
from fastapi import FastAPI, Form

app = FastAPI()

# 定义 POST 接口,接收表单数据
@app.post("/login/")
def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

文件上传 #

# 导入 FastAPI、UploadFile 和 File
from fastapi import FastAPI, UploadFile, File

app = FastAPI()

# 上传原始字节文件
@app.post("/files/")
def create_file(file: bytes = File(...)):
    return {"file_size": len(file)}

# 上传文件对象
@app.post("/uploadfile/")
def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

异常处理 #

# 导入 FastAPI 和 HTTPException
from fastapi import FastAPI, HTTPException

app = FastAPI()

# 假设有一个 items 字典存储数据
items = {"foo": "The Foo item", "bar": "The Bar item"}

# 定义带有异常处理的接口
@app.get("/items/{item_id}")
def read_item(item_id: str):
    # 如果 item_id 不在 items 中,抛出 404 异常
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    # 返回对应的 item
    return {"item": items[item_id]}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

中间件 #

# 导入 FastAPI 和 Request
from fastapi import FastAPI, Request
import time

app = FastAPI()

# 定义中间件,统计请求处理时间
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    # 记录开始时间
    start_time = time.time()
    # 处理请求
    response = await call_next(request)
    # 计算处理时间
    process_time = time.time() - start_time
    # 添加自定义响应头
    response.headers["X-Process-Time"] = str(process_time)
    return response

# 示例接口
@app.get("/")
async def root():
    return {"message": "Hello World"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

依赖注入 #

# 导入 FastAPI 和 Depends
from fastapi import FastAPI, Depends

app = FastAPI()

# 定义依赖函数,返回查询参数
def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

# 使用 Depends 注入依赖
@app.get("/items/")
def read_items(commons: dict = Depends(common_parameters)):
    return commons

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

安全性 #

# 导入 FastAPI 和 OAuth2PasswordBearer
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

# 创建 OAuth2PasswordBearer 实例,指定 tokenUrl
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# 依赖注入 token
@app.get("/items/")
def read_items(token: str = Depends(oauth2_scheme)):
    return {"token": token}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)

优势总结 #

  1. 自动文档:自动生成交互式 API 文档(Swagger UI 和 ReDoc)
  2. 数据验证:基于 Pydantic 的自动数据验证
  3. 异步支持:原生支持 async/await
  4. 类型安全:基于 Python 类型提示
  5. 生态系统:与 SQLAlchemy、Databases、Tortoise-ORM 等良好集成

FastAPI 非常适合构建高性能的现代 API,特别是需要快速开发和部署的项目。

访问验证

请输入访问令牌

Token不正确,请重新输入