plan_execute/app/main.py

109 lines
2.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""FastAPI 主应用模块。
定义 Web 路由和启动入口,提供 RESTful 风格的任务管理 API。
"""
from fastapi import FastAPI, HTTPException
from app.models import TodoCreate, TodoUpdate, TodoResponse, TodoListResponse
from app.services import todo_service
app = FastAPI(
title="Todo Manager API",
description="一个简单的任务管理器示例 API使用内存假数据。",
version="1.0.0",
)
@app.get("/api/todos", response_model=TodoListResponse, tags=["Todos"])
def list_todos():
"""获取所有任务列表。
Returns:
包含任务列表和总数的响应。
"""
items, total = todo_service.list_todos()
return TodoListResponse(data=items, total=total)
@app.get("/api/todos/{todo_id}", response_model=TodoResponse, tags=["Todos"])
def get_todo(todo_id: int):
"""根据 ID 获取单个任务。
Args:
todo_id: 任务唯一标识。
Returns:
包含任务详细信息的响应。
Raises:
HTTPException: 任务不存在时返回 404。
"""
item = todo_service.get_todo(todo_id)
if item is None:
raise HTTPException(status_code=404, detail=f"Todo with id {todo_id} not found")
return TodoResponse(data=item)
@app.post("/api/todos", response_model=TodoResponse, status_code=201, tags=["Todos"])
def create_todo(data: TodoCreate):
"""创建新任务。
Args:
data: 包含标题和描述的任务创建请求。
Returns:
包含新创建任务信息的响应。
"""
item = todo_service.create_todo(data)
return TodoResponse(code=201, message="created", data=item)
@app.put("/api/todos/{todo_id}", response_model=TodoResponse, tags=["Todos"])
def update_todo(todo_id: int, data: TodoUpdate):
"""更新已有任务。
Args:
todo_id: 要更新的任务 ID。
data: 包含需要更新字段的请求体。
Returns:
包含更新后任务信息的响应。
Raises:
HTTPException: 任务不存在时返回 404。
"""
item = todo_service.update_todo(todo_id, data)
if item is None:
raise HTTPException(status_code=404, detail=f"Todo with id {todo_id} not found")
return TodoResponse(data=item)
@app.delete("/api/todos/{todo_id}", response_model=TodoResponse, tags=["Todos"])
def delete_todo(todo_id: int):
"""删除指定任务。
Args:
todo_id: 要删除的任务 ID。
Returns:
删除成功的确认响应。
Raises:
HTTPException: 任务不存在时返回 404。
"""
deleted = todo_service.delete_todo(todo_id)
if not deleted:
raise HTTPException(status_code=404, detail=f"Todo with id {todo_id} not found")
return TodoResponse(message="deleted")
@app.get("/", tags=["Root"])
def root():
"""根路径,返回 API 基础信息。"""
return {
"name": "Todo Manager API",
"version": "1.0.0",
"docs": "/docs",
}