How to Create CRUD Operations in FastAPI Quickly
To create
CRUD operations in FastAPI, define API endpoints for each operation using HTTP methods like POST, GET, PUT, and DELETE. Use Pydantic models to validate data and a simple in-memory or database storage to manage records.Syntax
CRUD operations in FastAPI use these HTTP methods and decorators:
@app.post()for creating data@app.get()for reading data@app.put()for updating data@app.delete()for deleting data
Use Pydantic models to define the data structure for input and output. Each function handles one operation and returns JSON responses.
python
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): id: int name: str description: str | None = None items = {} @app.post("/items/") def create_item(item: Item): items[item.id] = item return item @app.get("/items/{item_id}") def read_item(item_id: int): return items.get(item_id, {"error": "Item not found"}) @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): if item_id in items: items[item_id] = item return item return {"error": "Item not found"} @app.delete("/items/{item_id}") def delete_item(item_id: int): return items.pop(item_id, {"error": "Item not found"})
Example
This example shows a simple FastAPI app with in-memory storage for items. It supports creating, reading, updating, and deleting items by their id. You can test it using tools like curl or Postman.
python
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): id: int name: str description: str | None = None items = {} @app.post("/items/") def create_item(item: Item): items[item.id] = item return item @app.get("/items/{item_id}") def read_item(item_id: int): return items.get(item_id, {"error": "Item not found"}) @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): if item_id in items: items[item_id] = item return item return {"error": "Item not found"} @app.delete("/items/{item_id}") def delete_item(item_id: int): if item_id in items: del items[item_id] return {"message": "Item deleted"} return {"error": "Item not found"}
Output
INFO: Started server process [12345]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Common Pitfalls
Common mistakes when creating CRUD in FastAPI include:
- Not validating input data with Pydantic models, which can cause errors or bad data.
- Using mutable default arguments or global variables incorrectly, leading to shared state bugs.
- Not handling missing items properly, causing server errors instead of user-friendly messages.
- Forgetting to use correct HTTP status codes for success and errors.
Always return clear JSON responses and handle errors gracefully.
python
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): id: int name: str items = {} # Wrong: No validation and no error handling @app.post("/items/") def create_item(item): # Missing type annotation items[item['id']] = item return item # Right: Use Pydantic model and check existence @app.post("/items/") def create_item(item: Item): if item.id in items: return {"error": "Item already exists"} items[item.id] = item return item
Quick Reference
FastAPI CRUD operations use these HTTP methods and decorators:
- Create:
@app.post("/path") - Read:
@app.get("/path/{id}") - Update:
@app.put("/path/{id}") - Delete:
@app.delete("/path/{id}")
Use Pydantic models to define request and response data shapes. Store data in a database or in-memory dictionary for testing.
Key Takeaways
Use FastAPI decorators with HTTP methods to define CRUD endpoints clearly.
Validate data with Pydantic models to avoid bad input and errors.
Handle missing data and errors gracefully with clear JSON responses.
Keep data storage simple for learning, then switch to databases for real apps.
Test your API endpoints with tools like curl or Postman to verify behavior.