Bird
Raised Fist0
FastAPIframework~10 mins

CRUD operations in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - CRUD operations
Receive HTTP Request
Identify Operation: Create, Read, Update, Delete
Process Data with Database
Return HTTP Response with Result
End
This flow shows how FastAPI handles CRUD operations by receiving a request, identifying the operation type, processing data, and returning a response.
Execution Sample
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

items = {}

class Item(BaseModel):
    name: str

@app.post('/items/')
async def create_item(id: int, item: Item):
    items[id] = item.name
    return items[id]

@app.get('/items/{id}')
async def read_item(id: int):
    return items.get(id, "Item not found")

@app.put('/items/{id}')
async def update_item(id: int, item: Item):
    items[id] = item.name
    return items[id]

@app.delete('/items/{id}')
async def delete_item(id: int):
    if id in items:
        del items[id]
    return "Item deleted"
This code implements basic CRUD operations (Create, Read, Update, Delete) using an in-memory dictionary to store items.
Execution Table
StepHTTP MethodEndpointInput DataActionData StateResponse
1POST/items/{id: 1, name: 'Book'}Create item with id=1{1: 'Book'}'Book'
2GET/items/1id=1Read item with id=1{1: 'Book'}'Book'
3PUT/items/1{name: 'Notebook'}Update item id=1{1: 'Notebook'}'Notebook'
4DELETE/items/1id=1Delete item with id=1{}Item deleted
5GET/items/1id=1Read item with id=1{}Item not found
💡 After deletion, item with id=1 no longer exists, so read returns 'Item not found'.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
items{}{1: 'Book'}{1: 'Book'}{1: 'Notebook'}{}{}
Key Moments - 3 Insights
Why does the GET request after deletion return 'Item not found'?
Because in step 4 the item with id=1 was deleted from the data store, so it no longer exists when step 5 tries to read it.
How does the PUT request update the item?
In step 3, the PUT request changes the value of items[1] from 'Book' to 'Notebook', updating the stored data.
What happens if we try to create an item with an existing id?
The new value will overwrite the old one in the dictionary, as shown in step 3 where the item is updated.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the state of 'items' after step 3?
A{}
B{1: 'Book'}
C{1: 'Notebook'}
D{1: 'Item deleted'}
💡 Hint
Check the 'Data State' column in row for step 3.
At which step does the item with id=1 get removed from the data?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look for the DELETE method in the 'HTTP Method' column.
If we send a POST request with id=1 and name='Pen' after step 4, what will be the new state of 'items'?
A{1: 'Notebook'}
B{1: 'Pen'}
C{}
D{1: 'Book'}
💡 Hint
POST creates or overwrites items; check how 'items' changes in step 1.
Concept Snapshot
CRUD operations in FastAPI:
- Create: POST /items/ with id and name to add item
- Read: GET /items/{id} to fetch item
- Update: PUT /items/{id} with new data
- Delete: DELETE /items/{id} to remove item
Data stored in a dictionary for simplicity.
Full Transcript
This visual execution shows how FastAPI handles CRUD operations using a simple dictionary as data storage. Each step corresponds to an HTTP request: POST creates an item, GET reads it, PUT updates it, and DELETE removes it. The execution table tracks the data state and responses after each operation. Beginners often wonder why reading after deletion fails or how updates overwrite data. The variable tracker shows how the 'items' dictionary changes over time. This step-by-step trace helps understand the flow of CRUD in FastAPI.

Practice

(1/5)
1. What does CRUD stand for in FastAPI applications?
easy
A. Cache, Route, Undo, Debug
B. Create, Read, Update, Delete
C. Compile, Render, Use, Deploy
D. Connect, Run, Upload, Download

Solution

  1. Step 1: Understand CRUD basics

    CRUD is a common acronym in web development representing the four basic operations on data.
  2. Step 2: Match CRUD to FastAPI operations

    FastAPI supports these operations: creating, reading, updating, and deleting data.
  3. Final Answer:

    Create, Read, Update, Delete -> Option B
  4. Quick 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
A. @app.put()
B. @app.get()
C. @app.post()
D. @app.delete()

Solution

  1. Step 1: Identify HTTP methods for CRUD

    Update operations typically use the HTTP PUT method.
  2. Step 2: Match HTTP method to FastAPI decorator

    FastAPI uses @app.put() to define routes that update existing data.
  3. Final Answer:

    @app.put() -> Option A
  4. Quick 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
A. 404 Not Found error
B. {"error": "Item not found"}
C. {"name": "Book", "price": 10.99}
D. Empty response

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    {"name": "Book", "price": 10.99} -> Option C
  4. Quick 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
A. Incorrect route path syntax
B. Missing return type annotation
C. Using async def instead of def
D. Deleting item without checking if it exists

Solution

  1. Step 1: Analyze deletion logic

    The code deletes the item directly without checking if the item_id exists in the dictionary.
  2. Step 2: Understand potential error

    If item_id is not in items, del will raise a KeyError causing a server error.
  3. Final Answer:

    Deleting item without checking if it exists -> Option D
  4. Quick 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 item
hard
A. Raises HTTPException with 404 status if missing
B. Returns error dict but no HTTP status code change
C. Updates without checking existence, no error if missing
D. Catches KeyError incorrectly, since assignment won't raise it

Solution

  1. Step 1: Understand proper 404 error handling in FastAPI

    FastAPI uses HTTPException to return HTTP errors with status codes.
  2. 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.
  3. Final Answer:

    Raises HTTPException with 404 status if missing -> Option A
  4. Quick 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