Bird
Raised Fist0
FastAPIframework~20 mins

CRUD operations in FastAPI - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
FastAPI CRUD Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this FastAPI GET endpoint?

Consider this FastAPI endpoint that returns a user by ID from a dictionary.

from fastapi import FastAPI, HTTPException
app = FastAPI()
users = {1: "Alice", 2: "Bob"}

@app.get("/users/{user_id}")
async def read_user(user_id: int):
    if user_id in users:
        return {"user": users[user_id]}
    raise HTTPException(status_code=404, detail="User not found")

What will be the JSON response when a client requests /users/2?

FastAPI
from fastapi import FastAPI, HTTPException
app = FastAPI()
users = {1: "Alice", 2: "Bob"}

@app.get("/users/{user_id}")
async def read_user(user_id: int):
    if user_id in users:
        return {"user": users[user_id]}
    raise HTTPException(status_code=404, detail="User not found")
A{"user": "Bob"}
B{"user": "Alice"}
C{"detail": "User not found"}
D404 Not Found error with empty body
Attempts:
2 left
💡 Hint

Check the dictionary key used to fetch the user.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a FastAPI POST endpoint to create a new item?

You want to create a POST endpoint in FastAPI that accepts a JSON body with a name field and returns the created item with an id.

Which code snippet is syntactically correct and follows FastAPI patterns?

A
from fastapi import FastAPI
app = FastAPI()

@app.post("/items")
async def create_item(name: str):
    return {"id": 1, "name": name}
B
from fastapi import FastAPI, Body
app = FastAPI()

@app.post("/items")
async def create_item(name: str = Body(...)):
    return {"id": 1, "name": name}
C
from fastapi import FastAPI
app = FastAPI()

@app.post("/items")
def create_item(name: str):
    return {"id": 1, "name": name}
D
from fastapi import FastAPI
app = FastAPI()

@app.post("/items")
async def create_item(name):
    return {"id": 1, "name": name}
Attempts:
2 left
💡 Hint

Think about how FastAPI extracts data from the request body.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI PUT endpoint raise a 422 Unprocessable Entity error?

Examine this FastAPI PUT endpoint meant to update a user's name:

from fastapi import FastAPI
app = FastAPI()
users = {1: "Alice", 2: "Bob"}

@app.put("/users/{user_id}")
async def update_user(user_id: int, name: str):
    if user_id in users:
        users[user_id] = name
        return {"user": users[user_id]}
    return {"error": "User not found"}

When a client sends a PUT request with JSON body {"name": "Charlie"}, the server responds with 422 error. Why?

FastAPI
from fastapi import FastAPI
app = FastAPI()
users = {1: "Alice", 2: "Bob"}

@app.put("/users/{user_id}")
async def update_user(user_id: int, name: str):
    if user_id in users:
        users[user_id] = name
        return {"user": users[user_id]}
    return {"error": "User not found"}
AThe users dictionary is empty, so update fails
BThe 'user_id' parameter is missing in the function signature
CThe endpoint is missing a return statement
DFastAPI expects 'name' as a query parameter, but client sent it in JSON body
Attempts:
2 left
💡 Hint

Check how FastAPI matches function parameters to request data.

state_output
advanced
2:00remaining
What is the state of the users dictionary after these FastAPI DELETE requests?

Given this FastAPI app:

from fastapi import FastAPI, HTTPException
app = FastAPI()
users = {1: "Alice", 2: "Bob", 3: "Charlie"}

@app.delete("/users/{user_id}")
async def delete_user(user_id: int):
    if user_id in users:
        del users[user_id]
        return {"message": "Deleted"}
    raise HTTPException(status_code=404, detail="User not found")

If a client sends DELETE requests to /users/2 then /users/3, what is the content of users afterwards?

FastAPI
from fastapi import FastAPI, HTTPException
app = FastAPI()
users = {1: "Alice", 2: "Bob", 3: "Charlie"}

@app.delete("/users/{user_id}")
async def delete_user(user_id: int):
    if user_id in users:
        del users[user_id]
        return {"message": "Deleted"}
    raise HTTPException(status_code=404, detail="User not found")
A{1: "Alice"}
B{2: "Bob", 3: "Charlie"}
C{}
D{1: "Alice", 2: "Bob", 3: "Charlie"}
Attempts:
2 left
💡 Hint

Think about what happens when you delete keys from a dictionary.

🧠 Conceptual
expert
2:00remaining
Which statement best describes idempotency in FastAPI CRUD operations?

Idempotency means that making the same request multiple times has the same effect as making it once.

Which FastAPI CRUD method is idempotent by design?

ADELETE endpoint that removes a resource and returns 404 if called again
BPATCH endpoint partially updating a resource with different data each time
CGET endpoint fetching a resource without changing state
DPOST endpoint creating a new resource each time it is called
Attempts:
2 left
💡 Hint

Think about which HTTP methods do not change server state.

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