FastAPI CRUD
FastAPI is a modern web framework for building APIs in Python. It provides automatic validation, interactive documentation, and high performance. This guide covers how to implement Create, Read, Update, and Delete (CRUD) operations using FastAPI.
Setting Up FastAPI
Install FastAPI and Uvicorn:
pip install fastapi uvicorn
Create a basic FastAPI app:
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Welcome to FastAPI"}
Run the server:
uvicorn main:app --reload
CRUD Operations with FastAPI
1. Create (POST)
Create a new resource by sending data in the request body.
from pydantic import BaseModel
class Customer(BaseModel):
name: str
email: str
active: bool
@app.post("/customers")
def create_customer(customer: Customer):
return {"message": "Customer created", "customer": customer}
2. Read (GET)
Fetch all resources or a specific resource.
@app.get("/customers")
def get_customers():
return {"customers": ["John Doe", "Jane Doe"]}
@app.get("/customers/{customer_id}")
def get_customer(customer_id: int):
return {"customer_id": customer_id, "name": "John Doe"}
3. Update (PUT)
Modify an existing resource.
@app.put("/customers/{customer_id}")
def update_customer(customer_id: int, customer: Customer):
return {"message": "Customer updated", "customer_id": customer_id, "customer": customer}
4. Delete (DELETE)
Remove a resource.
@app.delete("/customers/{customer_id}")
def delete_customer(customer_id: int):
return {"message": "Customer deleted", "customer_id": customer_id}
Running FastAPI with Uvicorn
Start the server:
uvicorn main:app --reload
Access the interactive API docs at:
- Swagger UI: http://127.0.0.1:8000/docs
- ReDoc: http://127.0.0.1:8000/redoc
CRUD Without REST
While REST is the standard for building CRUD, other alternatives include:
- GraphQL: Enables querying and mutating data flexibly.
- gRPC: Uses protocol buffers for high-performance communication.
Notable libraries and example projects
- FastAPI CRUD Example - Basic FastAPI CRUD application.
- FastAPI with SQLAlchemy - CRUD using SQLAlchemy and FastAPI.
- FastAPI + MongoDB CRUD - CRUD operations with MongoDB.
- FastAPI Users - User authentication and CRUD.