Bird
0
0

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:

hard📝 state output Q15 of 15
FastAPI - Database Integration
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
ARaises HTTPException with 404 status if missing
BReturns error dict but no HTTP status code change
CUpdates without checking existence, no error if missing
DCatches KeyError incorrectly, since assignment won't raise it
Step-by-Step Solution
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]
Quick Trick: Use HTTPException to return 404 errors in FastAPI [OK]
Common Mistakes:
MISTAKES
  • Returning error dict without HTTP status change
  • Assuming assignment raises KeyError
  • Not raising HTTPException for errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes