Mastering CRUD Operations with FastAPI: A Step-by-Step Guide

Suganthi
5 min readSep 10, 2024

--

In modern web development, building efficient APIs is a crucial skill. FastAPI is a fast, modern, and high-performance web framework that makes creating APIs a breeze, especially with its powerful type hints and auto-generated documentation. In this article, we will walk through setting up FastAPI and implementing CRUD (Create, Read, Update, Delete) operations to manage data.

Python: FastAPI: Swagger Documentation: ReDoc
Python: FastAPI - Swagger UI : FastAPI — ReDoc

What is FastAPI?

FastAPI is a Python web framework that allows developers to quickly create APIs with automatic validation and clear, concise code. It’s built on standard Python type hints, which enable fast development and provide features like data validation, auto-generated documentation (via Swagger and ReDoc), and performance on par with asynchronous frameworks.

Let’s dive in!

Step 1: Setting Up FastAPI

  1. Setting Up Environment

First, let’s set up our development environment:

  • Create a new directory for your project:- Organize your project by creating a directory:
mkdir fastapi_crud
cd fastapi_crud
  • Set up a virtual environment:-
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`

2. Install FastAPI and Uvicorn

To get started, install FastAPI and Uvicorn using pip:

  • What is Uvicorn? Uvicorn is a lightning-fast ASGI (Asynchronous Server Gateway Interface) server implementation, using uvloop and httptools.
  • Purpose: It’s primarily used to run asynchronous web applications and frameworks that are compatible with the ASGI specification, such as FastAPI.
pip install fastapi uvicorn

3. Create the Main FastAPI Application File

Inside your project directory, create a file called main.py:

touch main.py

4. Basic FastAPI Application

In main.py, add the following code to create a basic FastAPI app:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
return {"message": "Welcome to FastAPI CRUD!"}

5. Run the Application

Use Uvicorn to run your FastAPI application:

uvicorn main:app --reload

You should see output indicating the app is running. Open your browser and visit http://127.0.0.1:8000/ to see the welcome message.

Step 2: Creating a Model

For simplicity, we’ll manage a basic to-do list with FastAPI. Each to-do item will have an ID, title, description, and a status indicating if it’s completed.

  1. Pydantic Model
  • What is Pydantic? Pydantic is a Python library that uses type annotations to validate data and manage configurations. It enforces type hints at runtime and provides user-friendly errors when data is invalid.
  • Key Features: a) Data Validation: Automatically validates data based on Python type hints. b) Serialization: Can convert complex data types to JSON, dictionaries, or other formats. c) Settings Management: Helps manage configuration with support for environment variables and .env files. d) Custom Validators: Allows defining custom validation logic. e) Schema Generation: Can generate JSON Schema from Pydantic models.
  • How it works: Pydantic uses Python’s type hinting system to define the structure and types of data. When you create an instance of a Pydantic model, it validates the input data against these type definitions.

In main.py, let’s define a Todo model:

from pydantic import BaseModel
from typing import Optional

class Todo(BaseModel):
id: int
title: str
description: Optional[str] = None
completed: bool = False

This model defines what a to-do item looks like, with fields for id, title, description, and completed status.

Step 3: Implementing CRUD Operations

Now, let’s implement CRUD operations: Create, Read, Update, and Delete to manage to-do items.

  1. In-Memory Database
  • We use this simple in-memory database to focus on FastAPI’s CRUD operations without introducing the complexity of a full database system. In a real-world scenario, you’d typically replace this with a proper database like PostgreSQL, MySQL, or MongoDB.
  • It’s important to note that while we call this an “in-memory database”, it’s really just a Python list being used to store data temporarily. It serves the purpose of demonstrating how CRUD operations work in FastAPI without needing to set up a full database system.

For this article, we’ll use an in-memory list to store our to-do items:

todos = []

2. Create Operation

To add new to-do items, we will use the POST method.

@app.post("/todos/")
def create_todo(todo: Todo):
todos.append(todo)
return todo

Here, we define a create_todo function that accepts a Todo object and appends it to the todos list.

3. Read Operation

We’ll implement a GET method to retrieve the list of to-do items.

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

We simply return the todos list to get all the items.

To retrieve a specific item by ID, add the following route:

@app.get("/todos/{todo_id}")
def get_todo(todo_id: int):
for todo in todos:
if todo.id == todo_id:
return todo
return {"error": "To-do item not found!"}

This function filters the list to find the to-do item with the matching ID.

4. Update Operation

For updating existing items, we use the PUT method. Here’s the route for updating a to-do item:

@app.put("/todos/{todo_id}")
def update_todo(todo_id: int, updated_todo: Todo):
for index, todo in enumerate(todos):
if todo.id == todo_id:
todos[index] = updated_todo
return updated_todo
return {"error": "To-do item not found!"}

This function iterates through the todos list finds the matching item, and updates it with the new data.

5. Delete Operation

Finally, to delete an item, we’ll use the DELETE method:

@app.delete("/todos/{todo_id}")
def delete_todo(todo_id: int):
for index, todo in enumerate(todos):
if todo.id == todo_id:
todos.pop(index)
return {"message": "To-do item deleted!"}
return {"error": "To-do item not found!"}

This function removes the to-do item with the matching ID from the todos list.

Step 4: Testing the API

FastAPI provides automatic interactive documentation, making it easy to test your API. Visit http://127.0.0.1:8000/docs your browser, and you’ll see the Swagger UI, where you can test the different CRUD endpoints.

You can also view the ReDoc documentation at http://127.0.0.1:8000/redoc.

Python: FastAPI — Swagger UI
Python: FastAPI — Swagger UI
Python: FastAPI — Redoc
Python: FastAPI - Redoc

Conclusion

In this article, we’ve explored how to implement CRUD operations using FastAPI. From setting up the framework to creating, reading, updating, and deleting resources, FastAPI simplifies API development with its intuitive syntax and high performance.

Now that you’ve learned the basics of CRUD operations, you can extend this example by adding authentication, pagination, or integrating with a database. FastAPI is incredibly versatile and can handle both simple and complex APIs, making it a great choice for modern web development.

Happy coding!

Thanks for reading this article! 😊

--

--

Suganthi
Suganthi

Written by Suganthi

Always up for a challenge and eager to leverage technology to make a positive impact.