Home Backend Development Python Tutorial Part Building a Todo API with FastAPI: Step-by-Step Guide

Part Building a Todo API with FastAPI: Step-by-Step Guide

Aug 28, 2024 pm 06:32 PM

Part Building a Todo API with FastAPI: Step-by-Step Guide

Building a Todo API with FastAPI: Step-by-Step Guide

Code can be found here: GitHub - jamesbmour/blog_tutorials:

I. Introduction

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.

What We’ll Cover:

  • Designing the Todo Data Model
  • Implementing CRUD Operations
  • Creating API Endpoints
  • Adding Input Validation and Error Handling
  • Testing the API
  • Refactoring and Organizing Code

II. Designing the Todo Data Model

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.

A. Defining the Todo Schema

We’ll create two models using Pydantic:

  • TodoCreate: For input data when creating or updating a todo.
  • Todo: For the complete todo item, including fields like id and created_at.
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

Copy after login

B. Explaining the Fields

  • id: Unique identifier for each todo.
  • title: Main content of the todo.
  • description: Additional details (optional).
  • completed: Boolean status of the todo (whether it's done or not).
  • created_at: Timestamp indicating when the todo was created.

III. Creating CRUD Operations for Todos

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.

A. Setting Up an In-Memory Database

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(),
    },
]

Copy after login

B. Implementing Helper Functions

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

Copy after login

IV. Implementing API Endpoints

A. Creating a New Todo

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

Copy after login

B. Retrieving All Todos

The GET endpoint retrieves all todos from our in-memory database.

@app.get("/todos/", response_model=List[Todo])
def get_all_todos():
    return todos

Copy after login

C. Retrieving a Single Todo

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

Copy after login

D. Updating a 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)

Copy after login

E. Deleting a 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"}

Copy after login

V. Adding Input Validation and Error Handling

A. Input Validation with Pydantic

FastAPI automatically validates input data against the Pydantic models we defined. This ensures that the data meets our expected schema before it’s processed.

B. Custom Error Handling

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},
    )

Copy after login

VI. Testing the API

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.

Testing Example

  • Create a Todo: Test the POST endpoint by creating a new todo.
  • Retrieve Todos: Use the GET endpoints to fetch all todos or a specific one by id.
  • Update and Delete: Test the PUT and DELETE endpoints to update or remove a todo.

VII. Refactoring and Organizing Code

As the application grows, it’s essential to keep the code organized. Here are a few tips:

A. Moving Models to a Separate File

You can move your Pydantic models to a models.py file to keep your main application file clean.

B. Creating a Router for Todo Endpoints

Consider creating a separate router for todo-related endpoints, especially as your API grows.

VIII. Next Steps

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.

Suggested Improvements:

  • Add filtering and pagination to the GET endpoints.
  • Implement user authentication to manage personal todos.

IX. Conclusion

In this tutorial, we built a simple Todo API using FastAPI. We started by designing a data model, implemented CRUD operations, and created endpoints to manage todos. We also touched on input validation, error handling, and testing. With this foundation, you can extend the API further or integrate it with a frontend to create a full-fledged application.

If you would like to support my writing or buy me a beer:
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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles