from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from typing import List from uuid import uuid4, UUID router = APIRouter() class TodoCreate(BaseModel): title: str = Field(..., min_length=1) completed: bool = False class Todo(TodoCreate): id: UUID # In-memory storage todos: dict[UUID, Todo] = {} @router.get("/todos", response_model=List[Todo]) def list_todos(): return list(todos.values()) @router.post("/todos", response_model=Todo, status_code=201) def create_todo(todo: TodoCreate): todo_id = uuid4() new_todo = Todo(id=todo_id, **todo.dict()) todos[todo_id] = new_todo return new_todo @router.get("/todos/{todo_id}", response_model=Todo) def get_todo(todo_id: UUID): if todo_id not in todos: raise HTTPException(status_code=404, detail="Todo not found") return todos[todo_id] @router.put("/todos/{todo_id}", response_model=Todo) def update_todo(todo_id: UUID, todo: TodoCreate): if todo_id not in todos: raise HTTPException(status_code=404, detail="Todo not found") updated = Todo(id=todo_id, **todo.dict()) todos[todo_id] = updated return updated @router.delete("/todos/{todo_id}", status_code=204) def delete_todo(todo_id: UUID): if todo_id not in todos: raise HTTPException(status_code=404, detail="Todo not found") del todos[todo_id] return @router.delete("/todos", status_code=204) def clear_todos(): todos.clear() return