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 D
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:
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
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 A
Quick Check:
Use HTTPException for proper HTTP error responses [OK]
Hint: Use HTTPException to return 404 errors in FastAPI [OK]