CRUD operations let you create, read, update, and delete data in your app. They help manage information easily.
CRUD operations in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
FastAPI
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/") async def create_item(item: Item): items[item.id] = item return item @app.get("/items/{item_id}") async def read_item(item_id: int): return items.get(item_id) @app.put("/items/{item_id}") 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): return items.pop(item_id, None)
Use @app.post to create new data.
Use @app.get to read or get data.
Use @app.put to update existing data.
Use @app.delete to remove data.
Examples
FastAPI
from pydantic import BaseModel class User(BaseModel): id: int name: str users = {} @app.post("/users/") async def create_user(user: User): users[user.id] = user return user
FastAPI
@app.get("/users/{user_id}") async def read_user(user_id: int): return users.get(user_id)
FastAPI
@app.put("/users/{user_id}") async def update_user(user_id: int, user: User): users[user_id] = user return user
FastAPI
@app.delete("/users/{user_id}") async def delete_user(user_id: int): return users.pop(user_id, None)
Sample Program
This FastAPI app lets you add, get, update, and delete items using simple web requests. It stores items in a dictionary for easy access.
FastAPI
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/") async def create_item(item: Item): items[item.id] = item return {"message": "Item created", "item": item} @app.get("/items/{item_id}") async def read_item(item_id: int): item = items.get(item_id) if item: return item return {"error": "Item not found"} @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): if item_id in items: items[item_id] = item return {"message": "Item updated", "item": item} return {"error": "Item not found"} @app.delete("/items/{item_id}") async def delete_item(item_id: int): if item_id in items: removed = items.pop(item_id) return {"message": "Item deleted", "item": removed} return {"error": "Item not found"}
Important Notes
FastAPI uses Python type hints to check data automatically.
Use Pydantic models to define the shape of your data clearly.
Data is stored in memory here; for real apps, use a database.
Summary
CRUD means Create, Read, Update, Delete data.
FastAPI makes it easy to build these operations with simple decorators.
Use Pydantic models to define and validate your data.
Practice
1. What does CRUD stand for in FastAPI applications?
easy
Solution
Step 1: Understand CRUD basics
CRUD is a common acronym in web development representing the four basic operations on data.Step 2: Match CRUD to FastAPI operations
FastAPI supports these operations: creating, reading, updating, and deleting data.Final Answer:
Create, Read, Update, Delete -> Option BQuick Check:
CRUD = Create, Read, Update, Delete [OK]
Hint: Remember CRUD as the four main data actions [OK]
Common Mistakes:
- Confusing CRUD with unrelated terms
- Thinking CRUD includes deployment steps
- Mixing CRUD with HTTP methods only
2. Which FastAPI decorator is used to define a route for updating an existing item?
easy
Solution
Step 1: Identify HTTP methods for CRUD
Update operations typically use the HTTP PUT method.Step 2: Match HTTP method to FastAPI decorator
FastAPI uses @app.put() to define routes that update existing data.Final Answer:
@app.put() -> Option AQuick Check:
Update = @app.put() [OK]
Hint: Update uses PUT method and @app.put() decorator [OK]
Common Mistakes:
- Using @app.post() for update routes
- Confusing @app.get() with update
- Using @app.delete() instead of update
3. Given this FastAPI code snippet, what will be the response when accessing
GET /items/42 if the item exists?
from fastapi import FastAPI
app = FastAPI()
items = {42: {"name": "Book", "price": 10.99}}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return items.get(item_id, {"error": "Item not found"})medium
Solution
Step 1: Understand the dictionary lookup
The code uses items.get(item_id, {"error": "Item not found"}) which returns the item if found, else an error dict.Step 2: Check if item 42 exists
Item 42 is in the dictionary with name "Book" and price 10.99, so it will be returned.Final Answer:
{"name": "Book", "price": 10.99} -> Option CQuick Check:
Item found returns data, else error [OK]
Hint: dict.get returns value if key exists, else default [OK]
Common Mistakes:
- Assuming a 404 error is raised automatically
- Expecting an empty response if item exists
- Confusing error message with actual data
4. Identify the error in this FastAPI DELETE route code:
from fastapi import FastAPI
app = FastAPI()
items = {1: "apple", 2: "banana"}
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
del items[item_id]
return {"message": "Item deleted"}medium
Solution
Step 1: Analyze deletion logic
The code deletes the item directly without checking if the item_id exists in the dictionary.Step 2: Understand potential error
If item_id is not in items, del will raise a KeyError causing a server error.Final Answer:
Deleting item without checking if it exists -> Option DQuick Check:
Always check existence before deleting [OK]
Hint: Check key exists before deleting to avoid errors [OK]
Common Mistakes:
- Ignoring KeyError on missing keys
- Thinking async def causes error here
- Assuming route path syntax is wrong
5. You want to create a FastAPI endpoint to update an item only if it exists, otherwise return a 404 error. Which code snippet correctly implements this behavior?
A:
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
items[item_id] = item
return item
B:
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
if item_id not in items:
return {"error": "Not found"}
items[item_id] = item
return item
C:
from fastapi import HTTPException
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
items[item_id] = item
return item
D:
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
try:
items[item_id] = item
except KeyError:
return {"error": "Not found"}
return itemhard
Solution
Step 1: Understand proper 404 error handling in FastAPI
FastAPI uses HTTPException to return HTTP errors with status codes.Step 2: Analyze each option's error handling
The snippet using HTTPException(status_code=404, detail="Item not found") correctly returns a 404 response. Others either update without checking (200 OK), return an error dict as 200 OK, or misuse try-except since assignment does not raise KeyError.Final Answer:
Raises HTTPException with 404 status if missing -> Option AQuick Check:
Use HTTPException for proper HTTP error responses [OK]
Hint: Use HTTPException to return 404 errors in FastAPI [OK]
Common Mistakes:
- Returning error dict without HTTP status change
- Assuming assignment raises KeyError
- Not raising HTTPException for errors
