FastAPI开发Skill fastapi-development

FastAPI开发技能专注于使用Python的FastAPI框架高效构建高性能的异步Web API、后端服务和微服务。它涵盖了端点设计、Pydantic数据验证、依赖注入、自动文档生成和测试等关键技术。适用于需要快速开发、高并发处理和现代化API设计的场景。关键词:FastAPI, Python, 异步API, RESTful, Web后端, 微服务, Pydantic, 依赖注入, API开发, 高性能Web框架。

后端开发 4 次安装 106 次浏览 更新于 3/2/2026

名称: fastapi开发 描述: 使用FastAPI构建异步API,包括端点、依赖注入、验证和测试。适用于创建REST API、Web后端或微服务。

FastAPI开发

快速开始

创建一个基础的FastAPI应用:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

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

运行命令:

uv run uvicorn main:app --reload

常用模式

使用Pydantic模型进行验证

from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

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

依赖注入

from typing import Annotated
from fastapi import Depends

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

CommonsDep = Annotated[dict, Depends(common_parameters)]

@app.get("/items/")
async def read_items(commons: CommonsDep):
    return commons

带清理功能的数据库依赖

async def get_db():
    db = connect_to_database()
    try:
        yield db
    finally:
        db.close()

@app.get("/query/")
async def query_data(db: Annotated[dict, Depends(get_db)]):
    return {"data": "query results"}

错误处理

from fastapi import HTTPException

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id < 1:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}

路径和查询参数验证

from typing import Annotated
from fastapi import Path, Query

@app.get("/items/{item_id}")
async def read_item(
    item_id: Annotated[int, Path(gt=0, le=1000)],
    q: Annotated[str, Query(max_length=50)] = None
):
    return {"item_id": item_id, "q": q}

响应模型

from pydantic import BaseModel

class ItemPublic(BaseModel):
    id: int
    name: str
    price: float

@app.get("/items/{item_id}", response_model=ItemPublic)
async def read_item(item_id: int):
    return ItemPublic(id=item_id, name="Laptop", price=999.99)

使用TestClient进行测试

from fastapi.testclient import TestClient

client = TestClient(app)

def test_read_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"Hello": "World"}

def test_read_item():
    response = client.get("/items/42?q=test")
    assert response.status_code == 200
    assert response.json() == {"item_id": 42, "q": "test"}

依赖要求

uv add fastapi uvicorn
uv add "fastapi[all]"  # 包含所有可选依赖

核心概念

  • 异步/等待:对I/O操作使用async def
  • 自动验证:使用Pydantic进行请求/响应验证
  • 依赖注入:通过Depends在端点间共享逻辑
  • 类型提示:完整的编辑器支持和验证
  • 交互式文档:在/docs自动生成Swagger/OpenAPI文档
  • 后台任务:使用BackgroundTasks在响应后运行任务