🚀 使用 FastAPI + uv 构建 Todo App API(最简洁的方式!)

发布: (2025年12月27日 GMT+8 05:04)
2 min read
原文: Dev.to

Source: Dev.to

介绍

想要在没有 Python 包管理混乱的情况下构建一个闪电般快速的 API 吗?
在本指南中,我们将使用 FastAPIuv(下一代 Python 包管理器,自动化虚拟环境、处理依赖解析并且不干扰你的工作)来创建一个 Todo API。

什么是 uv

uv 是一个现代的 Python 包管理器,取代 pipvirtualenv,具备以下特性:

  • 🚀 超高速的依赖安装
  • 📦 自动创建虚拟环境
  • 🧼 零 requirements.txt 的更简洁项目设置

它使用 Rust 编写,适用于快速、可复现的 Python 工作流——非常适合 API、CLI 工具和数据应用。

项目初始化

mkdir fastapi-todo && cd fastapi-todo
uv init --app
uv add fastapi --extra standard

定义数据模型 (models.py)

# models.py
from pydantic import BaseModel

class Todo(BaseModel):
    id: int
    title: str
    completed: bool = False

构建 FastAPI 应用 (main.py)

# main.py
from fastapi import FastAPI, HTTPException
from models import Todo

app = FastAPI()
todos: list[Todo] = []

@app.get("/")
def home():
    return {"message": "Welcome to the FastAPI Todo App"}

@app.get("/todos")
def list_todos():
    return todos

@app.post("/todos", status_code=201)
def add_todo(todo: Todo):
    if any(t.id == todo.id for t in todos):
        raise HTTPException(status_code=400, detail="Todo with this ID already exists.")
    todos.append(todo)
    return todo

@app.put("/todos/{todo_id}")
def update(todo_id: int, updated: Todo):
    for i, t in enumerate(todos):
        if t.id == todo_id:
            todos[i] = updated
            return updated
    raise HTTPException(status_code=404, detail="Todo not found")

@app.delete("/todos/{todo_id}")
def delete(todo_id: int):
    global todos
    todos = [t for t in todos if t.id != todo_id]
    return {"message": "Todo deleted"}

运行应用

uv run fastapi dev

服务器将在 http://127.0.0.1:8000 启动。
在浏览器中打开交互式 API 文档进行探索。

Back to Blog

相关文章

阅读更多 »