使用 FastAPI 构建你的第一个 REST API:实用指南

发布: (2026年1月14日 GMT+8 00:06)
4 min read
原文: Dev.to

Source: Dev.to

为什么选择 FastAPI?

  • 性能:是目前最快的 Python 框架之一,可与 Node.js 和 Go 相媲美。
  • 类型安全:基于 Python 类型提示构建,提高代码质量并获得编辑器支持。
  • 自动文档:自动生成 Swagger UI 和 ReDoc 文档。
  • 现代 Python:使用 async/await 高效处理并发请求。

设置

首先,安装 FastAPI 和 uvicorn(一个 ASGI 服务器):

pip install fastapi uvicorn

创建一个简单的 API

以下是一个管理任务列表的基本 FastAPI 应用程序:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional

app = FastAPI()

# Pydantic model for data validation
class Task(BaseModel):
    id: int
    title: str
    description: Optional[str] = None
    completed: bool = False

# In-memory storage
tasks_db: List[Task] = []

@app.get("/")
def read_root():
    return {"message": "Welcome to the Task API"}

@app.get("/tasks", response_model=List[Task])
def get_tasks():
    return tasks_db

@app.get("/tasks/{task_id}", response_model=Task)
def get_task(task_id: int):
    task = next((t for t in tasks_db if t.id == task_id), None)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return task

@app.post("/tasks", response_model=Task, status_code=201)
def create_task(task: Task):
    tasks_db.append(task)
    return task

@app.put("/tasks/{task_id}", response_model=Task)
def update_task(task_id: int, updated_task: Task):
    for index, task in enumerate(tasks_db):
        if task.id == task_id:
            tasks_db[index] = updated_task
            return updated_task
    raise HTTPException(status_code=404, detail="Task not found")

@app.delete("/tasks/{task_id}")
def delete_task(task_id: int):
    for index, task in enumerate(tasks_db):
        if task.id == task_id:
            tasks_db.pop(index)
            return {"message": "Task deleted successfully"}
    raise HTTPException(status_code=404, detail="Task not found")

运行你的 API

启动开发服务器:

uvicorn main:app --reload

你的 API 现在正在 http://localhost:8000 上运行。

自动文档

FastAPI 开箱即提供交互式文档:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

您可以直接在浏览器中测试所有端点。

关键特性演示

  • Pydantic 模型Task 类使用 Pydantic 自动进行数据验证。无效数据会触发明确的错误响应。
  • 类型提示:代码中贯穿的 Python 类型提示提升了 IDE 支持并提前检测错误。
  • 路径参数:路由中的 {task_id} 语法会自动提取并验证 URL 参数。
  • HTTP 状态码:遵循 REST 最佳实践,使用适当的状态码(例如创建时的 201)。
  • 异常处理HTTPException 提供干净的错误响应并附带相应的状态码。

添加异步支持

FastAPI 在异步操作方面表现出色。下面是一个使用模拟异步数据库调用的示例:

import asyncio
from fastapi import HTTPException

@app.get("/tasks/async/{task_id}")
async def get_task_async(task_id: int):
    # Simulate async database call
    await asyncio.sleep(0.1)
    task = next((t for t in tasks_db if t.id == task_id), None)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return task

下一步

为了构建可投入生产的 API,请考虑:

  • 连接真实数据库(PostgreSQL、MongoDB)
  • 添加身份验证和授权
  • 实现全面的请求验证和错误处理
  • 为前端集成设置 CORS
  • 使用 pytest 编写测试
  • 使用 Docker 进行容器化

结论

FastAPI 让在 Python 中构建 API 变得直接且愉快。自动验证、文档生成以及现代 Python 特性减少了样板代码,让你专注于业务逻辑。它的性能和开发者体验使其成为小型项目和大规模应用的优秀选择。

Back to Blog

相关文章

阅读更多 »