How to Create CRUD Operations with FastAPI Quickly

In this post, we will explore how to quickly implement CRUD operations with FastAPI. We will start by setting up FastAPI and the database, then proceed to create the API endpoints for the CRUD operations.

David Demir

David Demir

17 May 2025

How to Create CRUD Operations with FastAPI Quickly

CRUD operations are essential in any web application that involves data storage and retrieval. These operations allow users to create new records, retrieve existing records, update existing records, and delete records from a database.

FastAPI makes it easy to implement CRUD operations by providing a simple and intuitive way to define API endpoints and handle HTTP requests. It leverages Python's type hints to automatically generate interactive API documentation and perform data validation, making it a powerful tool for building robust and well-documented APIs.

What is FastAPI
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use and to provide high performance for building APIs.

In this post, we will explore how to quickly implement CRUD operations with FastAPI. We will start by setting up FastAPI and the database, then proceed to create the API endpoints for the CRUD operations. We will also cover the implementation of the create, read, update, and delete operations, as well as testing and validating these operations. So let's get started and dive into the world of FastAPI and CRUD operations!

What is CRUD in FastAPI?

In FastAPI, CRUD refers to the basic operations that can be performed on data in a database or data storage system. CRUD stands for Create, Read, Update, and Delete, and it represents the fundamental functionalities that are essential for managing data in most applications.

Here's a detailed explanation of CRUD operations in FastAPI:

How to Create CRUD Operations with FastAPI Quickly

To implement CRUD functionality with FastAPI, follow these steps:

Step 1: Install FastAPI: Ensure that Python is installed on your system, and execute the following command in the command line to install FastAPI:

pip install fastapi

Step 2: Create a FastAPI Application: Create a new Python file (e.g., main.py) and import the required modules and libraries:

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

Step 3: Define Data Models: Use Pydantic to define data models. For example:

class Item(BaseModel):
    id: int
    name: str
    price: float

Step 4: Create CRUD Routes and Handlers: Use FastAPI to create routes and corresponding handling functions for CRUD operations. Here's an example:

items = []

@app.get("/items", response_model=List[Item])
async def read_items():
    return items

@app.post("/items", response_model=Item)
async def create_item(item: Item):
    items.append(item)
    return item

@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: int, item: Item):
    items[item_id] = item
    return item

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    del items[item_id]
    return {"message": "Item deleted"}

Step 5: Run the Application: To run the FastAPI application and test the APIRouter functionality, use an ASGI server like uvicorn. Make sure you have uvicorn installed:

pip install uvicorn

In your IDE editor, open the terminal, navigate to the directory where the main.py file is stored, and run the following command to start the application:

uvicorn main:app --reload

This will start the FastAPI application on the default port (usually 8000) with auto-reloading enabled, so the application will reload automatically when you make code changes.

Step 6: Test CRUD Operation

Use an HTTP client tool (e.g., cURL or Apidog) to send requests and test the Create, Read, Update, and Delete functionalities. Here are some example requests:

POST http://localhost:8000/items
{
    "id": 1,
    "name": "Apple",
    "price": 0.5
}
 a POST request
GET http://localhost:8000/items
a GET request
GET http://localhost:8000/items
a PUT request
DELETE http://localhost:8000/items/1
 a DELETE request

Lastly, we can write tests for the delete operation in Apidog. We can simulate a DELETE request to the delete endpoint and check if the response status code is 200 (indicating a successful deletion). We can then try to retrieve the deleted data from the database and ensure that it does not exist.

By writing these tests, we can ensure that our CRUD operations are working correctly and handle different scenarios, such as invalid input or non-existent data.

Bonus Tips

Use IDE support like Visual Studio Code for improved development efficiency with code autocompletion, error checking, and debugging features.

By following these practices, you can develop robust and efficient APIs with FastAPI, streamlining your development and deployment process.

Explore more

REST API Pagination: An In-Depth Guide

REST API Pagination: An In-Depth Guide

In the world of modern application development, REST APIs serve as the fundamental communication layer, enabling disparate systems to exchange data seamlessly. As applications grow in scale and complexity, so does the volume of data they handle. Requesting an entire dataset, potentially containing millions or even billions of records, in a single API call is inefficient, unreliable, and a significant performance bottleneck. This is where a crucial technique in API design and development comes in

7 June 2025

How to Use the new Gemini 2.5 06-05 Pro API

How to Use the new Gemini 2.5 06-05 Pro API

Learn how to use the Gemini 2.5 06-05 Pro API in this technical guide. Set up, authenticate, and explore multimodal and coding features of Google’s powerful AI model. Perfect for developers building advanced apps!

6 June 2025

How to Use Deepseek R1 Locally with Cursor

How to Use Deepseek R1 Locally with Cursor

Learn how to set up and configure local DeepSeek R1 with Cursor IDE for private, cost-effective AI coding assistance.

4 June 2025

Practice API Design-first in Apidog

Discover an easier way to build and use APIs