Code can be found here: GitHub - jamesbmour/blog_tutorials:
In the previous post, we introduced FastAPI and set up a basic project structure. Now, we’ll take it a step further by building a functional Todo API. By the end of this tutorial, you’ll have a working backend that can create, read, update, and delete todo items.
To manage todos, we must define a data model representing a todo item. FastAPI uses Pydantic models to validate and parse data, so we’ll leverage that here.
We’ll create two models using Pydantic:
from pydantic import BaseModel from typing import Optional from datetime import datetime class TodoCreate(BaseModel): title: str description: Optional[str] = None completed: bool = False class Todo(BaseModel): id: str title: str description: Optional[str] = None completed: bool created_at: datetime
CRUD stands for Create, Read, Update, and Delete—the four basic operations for managing data. We’ll implement these operations using an in-memory database (a simple list) for this tutorial.
We’ll use a list to store our todos. For simplicity, we’ll also add a few example todos.
from uuid import uuid4 from datetime import datetime todos = [ { "id": str(uuid4()), "title": "Learn FastAPI", "description": "Go through the official FastAPI documentation and tutorials.", "completed": False, "created_at": datetime.now(), }, { "id": str(uuid4()), "title": "Build a Todo API", "description": "Create a REST API for managing todo items using FastAPI.", "completed": False, "created_at": datetime.now(), }, { "id": str(uuid4()), "title": "Write blog post", "description": "Draft a blog post about creating a Todo API with FastAPI.", "completed": False, "created_at": datetime.now(), }, ]
We’ll implement a simple helper function to find a todo by its id.
def get_todo_by_id(todo_id: str): for todo in todos: if todo["id"] == todo_id: return todo return None
The POST endpoint allows users to create a new todo item.
@app.post("/todos/", response_model=Todo) def create_todo(todo: TodoCreate): new_todo = Todo( id=str(uuid4()), title=todo.title, description=todo.description, completed=todo.completed, created_at=datetime.now() ) todos.append(new_todo.dict()) return new_todo
The GET endpoint retrieves all todos from our in-memory database.
@app.get("/todos/", response_model=List[Todo]) def get_all_todos(): return todos
The GET endpoint allows retrieving a single todo by its id.
@app.get("/todos/{todo_id}", response_model=Todo) def get_todo(todo_id: str): todo = get_todo_by_id(todo_id) if not todo: raise HTTPException(status_code=404, detail="Todo not found") return todo
The PUT endpoint allows users to update an existing todo.
@app.put("/todos/{todo_id}", response_model=Todo) def update_todo(todo_id: str, todo_data: TodoCreate): todo = get_todo_by_id(todo_id) if not todo: raise HTTPException(status_code=404, detail="Todo not found") todo["title"] = todo_data.title todo["description"] = todo_data.description todo["completed"] = todo_data.completed return Todo(**todo)
The DELETE endpoint allows users to delete a todo by its id.
@app.delete("/todos/{todo_id}") def delete_todo(todo_id: str): todo = get_todo_by_id(todo_id) if not todo: raise HTTPException(status_code=404, detail="Todo not found") todos.remove(todo) return {"detail": "Todo deleted successfully"}
FastAPI automatically validates input data against the Pydantic models we defined. This ensures that the data meets our expected schema before it’s processed.
We can customize error responses by adding an exception handler.
@app.exception_handler(HTTPException) def http_exception_handler(request, exc: HTTPException): return JSONResponse( status_code=exc.status_code, content={"detail": exc.detail}, )
FastAPI comes with interactive Swagger UI documentation, making it easy to test your API endpoints. Simply run the application and navigate to /docs in your browser.
As the application grows, it’s essential to keep the code organized. Here are a few tips:
You can move your Pydantic models to a models.py file to keep your main application file clean.
Consider creating a separate router for todo-related endpoints, especially as your API grows.
In the next post, we’ll integrate a real database (like SQLite or PostgreSQL) into our FastAPI application. We’ll also look into user authentication and more advanced features.
このチュートリアルでは、FastAPI を使用して単純な Todo API を構築しました。データ モデルの設計から開始し、CRUD 操作を実装し、ToDo を管理するためのエンドポイントを作成しました。入力検証、エラー処理、テストについても触れました。この基盤を使用すると、API をさらに拡張したり、フロントエンドと統合して本格的なアプリケーションを作成したりできます。
私の執筆をサポートしたり、ビールを買ったりしたい場合は:
https://buymeacoffee.com/bmours
The above is the detailed content of Part Building a Todo API with FastAPI: Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!