FastAPI Item Update and Delete Endpoints
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
You are given the core handler layer of an item-catalog REST API modeled after FastAPI in pure Python. The module already provides:
HTTPException(status_code: int, detail: Any)— mirrorsfastapi.HTTPException, representing an HTTP error response(status_code, {"detail": detail}).parse_item_in(payload: Any) -> Dict[str, Any]— mirrors a sharedItemInPydantic request model and raisesHTTPException(422, ...)on any schema violation.ItemStore— an injected in-memory store holdingitems: Dict[int, Dict[str, Any]]and an auto-incrementingnext_id: intstarting at1.- Two completed handlers:
create_item(store: ItemStore, payload: Any) -> Tuple[int, Dict[str, Any]](POST /items->201with a shallow copy of the stored item, or422).read_item(store: ItemStore, item_id: int) -> Tuple[int, Dict[str, Any]](GET /items/{item_id}->200with a shallow copy of the stored item, or404).
Complete the CRUD surface by implementing update_item and delete_item with the exact signatures below:
def update_item(store: ItemStore, item_id: int, payload: Any) -> Tuple[int, Dict[str, Any]]:
...
def delete_item(store: ItemStore, item_id: int) -> Tuple[int, None]:
...
Endpoint requirements:
update_item(PUT /items/{item_id}):- Validate
payloadviaparse_item_in(payload)before checking whetheritem_idexists instore.items, so invalid payloads raiseHTTPException(422, ...)even whenitem_idis absent (matching FastAPI's schema-first pipeline). - If
item_idis not present instore.items, raiseHTTPException(404, "Item not found")without inserting anything or modifyingstore.next_id. - Perform a full replacement of
store.items[item_id]keeping"id": item_idfrom the URL path (any omitted optional"description"resets toNone), and return(200, copy_of_record)as a shallow copy so caller edits cannot mutate stored data. Sending the same validPUTrepeatedly must be idempotent.
- Validate
delete_item(DELETE /items/{item_id}):- If
item_idis not instore.items, raiseHTTPException(404, "Item not found"). - Otherwise delete
store.items[item_id]without decrementingstore.next_id(deleted IDs are never recycled) and return(204, None)(204 No Content). RepeatingDELETEon an already-deleted ID raisesHTTPException(404, "Item not found")while leaving stored state unchanged.
- If
In addition to passing unit tests across all four handlers, be prepared to explain how an engineer unfamiliar with FastAPI can derive PUT and DELETE cleanly using the existing POST/GET handlers as templates alongside targeted framework documentation.
Examples
Example 1
store = ItemStore()
create_item(store, {"name": "lamp", "price": 24.5, "description": "brass desk lamp"})
# -> (201, {"id": 1, "name": "lamp", "price": 24.5, "description": "brass desk lamp"})
update_item(store, 1, {"name": "floor lamp", "price": 39})
# -> (200, {"id": 1, "name": "floor lamp", "price": 39.0, "description": None})
update_item(store, 99, {"name": "", "price": 10})
# -> raises HTTPException(422, "name: a string of 1 to 100 characters is required")
Walk-through: Creating "lamp" assigns id = 1. Calling update_item on 1 validates the new body, normalizes 39 to 39.0, resets the omitted "description" field to None, replaces record 1 in full, and returns (200, ...). Sending an empty "name" to nonexistent ID 99 raises 422 rather than 404 because body validation runs first.
Example 2
store = ItemStore()
create_item(store, {"name": "kettle", "price": 18}) # -> (201, {"id": 1, ...})
create_item(store, {"name": "toaster", "price": 32}) # -> (201, {"id": 2, ...})
delete_item(store, 2)
# -> (204, None)
delete_item(store, 2)
# -> raises HTTPException(404, "Item not found")
create_item(store, {"name": "blender", "price": 45})
# -> (201, {"id": 3, "name": "blender", "price": 45.0, "description": None})
Walk-through: Deleting item 2 removes "toaster" and returns (204, None). A second delete_item(store, 2) sees item 2 is absent and raises HTTPException(404, "Item not found") while keeping store.items unchanged ({1: ...}). Creating "blender" next receives id = 3 because store.next_id is never rolled back on deletion.
Constraints
payloadforPOSTandPUTmust be adictcontaining only keys in("name", "price", "description"); unknown keys (including"id") raiseHTTPException(422, ...).name: requiredstrwith1 <= len(name) <= 100.price: requiredintorfloat(notbool) strictly greater than0, stored asfloat.description: optional (Nonewhen omitted) orstrwithlen(description) <= 500.- Returned item dictionaries from
create_item,read_item, andupdate_itemmust be copies disconnected fromstore.items.
Step-by-step walkthrough
Learn an unfamiliar framework from the existing endpoints
CRUD stands for the four core resource operations in an API: Create, Read, Update, and Delete. Even if you have never touched FastAPI before, the two working endpoints act as a complete Rosetta Stone:
@app.post("/items", response_model=Item, status_code=201) <-- HTTP verb + path, output schema, success code def create_item(item: ItemIn, store = Depends(get_store)): <-- ItemIn: Pydantic body model (auto-validated) <-- Depends(...): injected store (swappable in tests) @app.get("/items/{item_id}", response_model=Item) <-- {item_id} in URL path... def read_item(item_id: int, store = Depends(get_store)): <-- ...arrives parsed as a Python int if item_id not in store.items: raise HTTPException(status_code=404, detail="...") <-- how expected HTTP errors exit an endpointThree FastAPI building blocks appear right in those ten lines: 1. Pydantic models (
ItemIn,Item): Python classes whose type hints FastAPI uses to validate incoming JSON requests and serialize outgoing JSON responses automatically. 2. Dependency injection (Depends): Passing shared collaborators (such as a store or database session) into an endpoint as function parameters so unit tests can substitute an isolated test store. 3. Pattern reuse + targeted docs: Run the existing test suite first to confirm your environment works, inspect FastAPI's auto-generated interactive docs at/docs, and read only the matching official tutorial pages ("Path Parameters", "Request Body", "Response Status Code", "Handling Errors", and "Testing"). Notice thatupdate_itemis simply create's body validation + read's 404 check, anddelete_itemis read's 404 check + removal!Lock down REST status codes and idempotency
Before coding, write down the exact HTTP contract for all four endpoints so status codes, response bodies, and retry behavior stay consistent:
Method & Path Request Body Success Response Error Responses ----------------------------------------------------------------------------------------------- POST /items ItemIn JSON 201 Created + Item 422 invalid JSON / field rules GET /items/{id} (none) 200 OK + Item 404 unknown id | 422 non-int id PUT /items/{id} ItemIn JSON 200 OK + Item 404 unknown id | 422 invalid body/id DELETE /items/{id} (none) 204 No Content (empty) 404 unknown id | 422 non-int idThree REST rules govern
PUTandDELETEhere: -PUTreplaces the entire resource: Omitting an optional field likedescriptionresets it to its default (None), rather than keeping the old description (partial field-by-field updates belong toPATCH). -PUTdoes not create new IDs: BecausePOSTowns ID generation (1, 2, 3, ...), sendingPUT /items/999for a missing ID must return404 Not Foundrather than silently creating item999. - Idempotency: An operation is idempotent if sending the exact same request multiple times leaves the server's stored state identical to sending it once. Notice that idempotency is about server state, not always getting the identical status code:Request Response Server State After Call -------------------------------------------------------------------------------------------------------------------- POST /items {"name":"lamp","price":24.5} 201 {"id":1, "price":24.5, ...} {1: lamp @ 24.5} PUT /items/1 {"name":"floor lamp","price":39.0} 200 {"id":1, "price":39.0, ...} {1: floor lamp @ 39.0} PUT /items/1 {"name":"floor lamp","price":39.0} 200 {"id":1, "price":39.0, ...} {1: floor lamp @ 39.0} (same!) DELETE /items/1 204 (empty body) {} (item 1 gone) DELETE /items/1 404 {"detail":"Item not found"} {} (still gone -> idempotent!) POST /items {"name":"blender","price":45.0} 201 {"id":2, "price":45.0, ...} {2: blender @ 45.0} (ID 1 not reused)Understand FastAPI's validation order and error pipeline
In FastAPI, path parameters and Pydantic request bodies are validated before your endpoint function ever starts executing, returning 422 Unprocessable Content (valid JSON syntax whose field types or constraints fail validation) on any mismatch:
Client Request: PUT /items/999 {"name": "", "price": -5} │ ▼ [1. FastAPI + Pydantic Schema Check] ──(invalid body or path)──► 422 Unprocessable Content │ (valid ItemIn + int item_id) ▼ [2. Endpoint Function: Check Store] ──(item_id missing)───────► 404 Not Found │ (item_id exists) ▼ [3. Replace Record & Serialize Copy] ──────────────────────────► 200 OK + Item JSONTwo important details follow directly from this pipeline: 1. Validation precedes 404: Sending an invalid body (
{"name": ""}) to a nonexistent path (/items/999) must return 422, not 404. 2. Single shared schema withextra="forbid": ReusingItemInfor bothPOSTandPUTguarantees identical rules, and forbidding unknown fields rejects bodies containing"id": 9so the item's ID can only ever come from the URL path.Review the self-contained sandbox skeleton
So our code and tests run anywhere without external packages, the sandbox models FastAPI's boundary with
HTTPException,parse_item_in, andItemStore, alongside the two workingcreate_itemandread_itemfunctions:from typing import Any, Dict, Tuple class HTTPException(Exception): """Mirrors fastapi.HTTPException: FastAPI converts this into HTTP status_code + {"detail": detail}.""" def __init__(self, status_code: int, detail: Any) -> None: super().__init__(detail) self.status_code = status_code self.detail = detail ITEM_FIELDS = ("name", "price", "description") def parse_item_in(payload: Any) -> Dict[str, Any]: """Validate a request body against the ItemIn schema; raise HTTPException(422) on any violation.""" if not isinstance(payload, dict): raise HTTPException(422, "body must be a JSON object") for key in payload: if key not in ITEM_FIELDS: raise HTTPException(422, f"unknown field: {key}") name = payload.get("name") if not isinstance(name, str) or not 1 <= len(name) <= 100: raise HTTPException(422, "name: a string of 1 to 100 characters is required") price = payload.get("price") # Check isinstance(price, bool) first because bool is a subclass of int in Python (isinstance(True, int) == True). if isinstance(price, bool) or not isinstance(price, (int, float)) or not price > 0: raise HTTPException(422, "price: a number greater than 0 is required") description = payload.get("description") if description is not None: if not isinstance(description, str) or len(description) > 500: raise HTTPException(422, "description: a string of at most 500 characters, or null") return {"name": name, "price": float(price), "description": description} class ItemStore: """In-memory storage injected into endpoints (stands in for a database session).""" def __init__(self) -> None: self.items: Dict[int, Dict[str, Any]] = {} self.next_id: int = 1 def _make_item(item_id: int, fields: Dict[str, Any]) -> Dict[str, Any]: """Build a complete stored item record from the path/assigned ID and validated ItemIn fields.""" return { "id": item_id, "name": fields["name"], "price": fields["price"], "description": fields["description"], } def create_item(store: ItemStore, payload: Any) -> Tuple[int, Dict[str, Any]]: """POST /items -> 201 and the created item, or 422 for an invalid body.""" fields = parse_item_in(payload) item = _make_item(store.next_id, fields) store.items[item["id"]] = item store.next_id += 1 return 201, dict(item) def read_item(store: ItemStore, item_id: int) -> Tuple[int, Dict[str, Any]]: """GET /items/{item_id} -> 200 and the item, or 404 if missing.""" item = store.items.get(item_id) if item is None: raise HTTPException(404, "Item not found") return 200, dict(item)Implement update_item (PUT /items/{item_id})
Combine the exact pieces from
create_itemandread_itemin order: 1. Validatepayloadwithparse_item_in(payload)first (422on invalid input, even ifitem_iddoes not exist). 2. Checkif item_id not in store.items:and raiseHTTPException(404, "Item not found"). 3. Build a brand-new dictionary via_make_item(item_id, fields)—ensuring omitted optional fields reset cleanly toNone—store it atstore.items[item_id]without touchingstore.next_id, and return(200, dict(replaced_item)):def update_item(store: ItemStore, item_id: int, payload: Any) -> Tuple[int, Dict[str, Any]]: """PUT /items/{item_id} -> 200 and the replaced item; 422 on bad body; 404 if item_id is missing.""" fields = parse_item_in(payload) if item_id not in store.items: raise HTTPException(404, "Item not found") replaced_item = _make_item(item_id, fields) store.items[item_id] = replaced_item return 200, dict(replaced_item)Implement delete_item (DELETE /items/{item_id})
Check existence just like
read_item, remove the item fromstore.items, leavestore.next_idunchanged so old deleted IDs are never recycled onto future items, and return(204, None)to represent HTTP204 No Content:def delete_item(store: ItemStore, item_id: int) -> Tuple[int, None]: """DELETE /items/{item_id} -> 204 with no body, or 404 if item_id does not exist.""" if item_id not in store.items: raise HTTPException(404, "Item not found") del store.items[item_id] return 204, NoneMap the endpoints and isolated unit tests to real FastAPI
In a real FastAPI codebase,
parse_item_inbecomes the sharedItemInPydantic model, andupdate_item/delete_itemsit right beside@app.postand@app.get:from typing import Optional from fastapi import Depends, FastAPI, HTTPException, Response, status from pydantic import BaseModel, ConfigDict, Field app = FastAPI() class ItemIn(BaseModel): model_config = ConfigDict(extra="forbid") name: str = Field(min_length=1, max_length=100) price: float = Field(gt=0) description: Optional[str] = Field(default=None, max_length=500) class Item(ItemIn): id: int class ItemStore: def __init__(self) -> None: self.items: dict[int, Item] = {} self.next_id = 1 _default_store = ItemStore() def get_store() -> ItemStore: return _default_store @app.put("/items/{item_id}", response_model=Item) def update_item(item_id: int, item: ItemIn, store: ItemStore = Depends(get_store)) -> Item: if item_id not in store.items: raise HTTPException(status_code=404, detail="Item not found") updated = Item(id=item_id, **item.model_dump()) store.items[item_id] = updated return updated @app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_item(item_id: int, store: ItemStore = Depends(get_store)) -> Response: if item_id not in store.items: raise HTTPException(status_code=404, detail="Item not found") del store.items[item_id] return Response(status_code=status.HTTP_204_NO_CONTENT)For unit testing all four endpoints with
fastapi.testclient.TestClient, overrideapp.dependency_overrides[get_store]inside apytestfixture so every test starts with a freshItemStoreand test execution order can never cause flaky failures:import pytest from fastapi.testclient import TestClient @pytest.fixture def client(): fresh = ItemStore() app.dependency_overrides[get_store] = lambda: fresh yield TestClient(app) app.dependency_overrides.clear()Complete solution
from typing import Any, Dict, Tuple # Self-contained endpoint logic for a FastAPI items CRUD service. # HTTPException and parse_item_in mirror fastapi.HTTPException and a shared Pydantic ItemIn model. class HTTPException(Exception): """Mirrors fastapi.HTTPException: FastAPI converts this into HTTP status_code + {"detail": detail}.""" def __init__(self, status_code: int, detail: Any) -> None: super().__init__(detail) self.status_code = status_code self.detail = detail ITEM_FIELDS = ("name", "price", "description") def parse_item_in(payload: Any) -> Dict[str, Any]: """Validate a request body against the ItemIn schema; raise HTTPException(422) on any violation.""" if not isinstance(payload, dict): raise HTTPException(422, "body must be a JSON object") # Forbid unknown fields (like Pydantic extra="forbid") so a body "id" cannot override the path id. for key in payload: if key not in ITEM_FIELDS: raise HTTPException(422, f"unknown field: {key}") name = payload.get("name") if not isinstance(name, str) or not 1 <= len(name) <= 100: raise HTTPException(422, "name: a string of 1 to 100 characters is required") price = payload.get("price") # Check isinstance(price, bool) first because bool is a subclass of int in Python (isinstance(True, int) == True). if isinstance(price, bool) or not isinstance(price, (int, float)) or not price > 0: raise HTTPException(422, "price: a number greater than 0 is required") description = payload.get("description") if description is not None: if not isinstance(description, str) or len(description) > 500: raise HTTPException(422, "description: a string of at most 500 characters, or null") return {"name": name, "price": float(price), "description": description} class ItemStore: """In-memory storage injected into endpoints (stands in for a database session).""" def __init__(self) -> None: # items: item_id -> stored record dict, e.g. {1: {"id": 1, "name": "lamp", "price": 24.5, "description": None}} self.items: Dict[int, Dict[str, Any]] = {} # next_id: monotonically increasing auto-increment ID; never decremented on delete self.next_id: int = 1 def _make_item(item_id: int, fields: Dict[str, Any]) -> Dict[str, Any]: """Build a complete stored item record from the path/assigned ID and validated ItemIn fields.""" return { "id": item_id, "name": fields["name"], "price": fields["price"], "description": fields["description"], } # ----- Given: the two working endpoints ----- def create_item(store: ItemStore, payload: Any) -> Tuple[int, Dict[str, Any]]: """POST /items -> 201 and the created item, or 422 for an invalid body.""" fields = parse_item_in(payload) item = _make_item(store.next_id, fields) store.items[item["id"]] = item store.next_id += 1 # Return a shallow copy so caller edits to the response cannot mutate stored state. return 201, dict(item) def read_item(store: ItemStore, item_id: int) -> Tuple[int, Dict[str, Any]]: """GET /items/{item_id} -> 200 and the item, or 404 if missing.""" item = store.items.get(item_id) if item is None: raise HTTPException(404, "Item not found") return 200, dict(item) # ----- Implemented: update and delete matching the existing contract ----- def update_item(store: ItemStore, item_id: int, payload: Any) -> Tuple[int, Dict[str, Any]]: """PUT /items/{item_id} -> 200 and the replaced item; 422 on bad body; 404 if item_id is missing.""" # Phase 1: Validate body BEFORE checking existence, matching FastAPI's Pydantic-first pipeline. fields = parse_item_in(payload) # Phase 2: Reject unknown IDs with 404 so PUT cannot create arbitrary client-chosen IDs. if item_id not in store.items: raise HTTPException(404, "Item not found") # Phase 3: Replace the entire record (omitted optional fields reset to None) and return a copy. replaced_item = _make_item(item_id, fields) store.items[item_id] = replaced_item return 200, dict(replaced_item) def delete_item(store: ItemStore, item_id: int) -> Tuple[int, None]: """DELETE /items/{item_id} -> 204 with no body, or 404 if item_id does not exist.""" if item_id not in store.items: raise HTTPException(404, "Item not found") # Remove the record without touching store.next_id so deleted IDs are never reused. del store.items[item_id] return 204, None✅ Submit now — all tests should pass.
Intuition & how it works
Picture a library catalog drawer of numbered index cards (1, 2, 3, ...) guarded by an intake clerk (Pydantic validation, a schema checker that verifies field names, types, and limits before the handler runs). Creating an item (POST /items) hands a validated form to the librarian, who stamps it with the next unused number and returns 201 Created. Updating (PUT /items/{id}) first passes the intake clerk's check (422 if invalid), verifies slot id actually exists (404 if empty), and swaps out the entire card in slot id (200 OK). Deleting (DELETE /items/{id}) removes card id from the drawer (204 No Content with an empty body, or 404 if that slot is already empty) without rolling back the numbering stamp.
Why do hasty implementations fail? Updating an existing dictionary key-by-key (stored.update(payload)) turns full-replacement PUT into a partial PATCH where omitted optional fields keep stale old values; forgetting if item_id not in store.items lets clients invent arbitrary IDs via PUT; and checking 404 before validating the JSON body disagrees with FastAPI, which validates request schemas before entering the endpoint function.
Trace four requests from the examples against an initially empty ItemStore to see the exact state transitions:
1. POST /items {"name": "lamp", "price": 24.5, "description": "brass desk lamp"} -> validates body, assigns id = 1, advances next_id to 2, and returns (201, {"id": 1, "name": "lamp", "price": 24.5, "description": "brass desk lamp"}).
2. PUT /items/1 {"name": "floor lamp", "price": 39} -> validates body (description defaults to None), finds 1 in store.items, replaces card 1 completely, and returns (200, {"id": 1, "name": "floor lamp", "price": 39.0, "description": None}). Repeating this exact PUT returns the exact same 200 result and leaves state unchanged (idempotent, meaning repeating a request has the same effect on stored state as calling it once).
3. DELETE /items/1 -> finds 1, deletes store.items[1] while keeping next_id = 2, and returns (204, None).
4. DELETE /items/1 a second time -> sees 1 not in store.items and raises HTTPException(404, "Item not found"), leaving the store in the exact same empty state (idempotent on server state).
Complexity
Let N be the number of stored items and B be the character size of the incoming JSON request body:
- Time:
O(B)percreate_itemandupdate_itemrequest to inspect the keys and string lengths of the incoming payload plusO(1)average time to look up or assignstore.items[item_id];O(1)average time perread_itemanddelete_itemrequest for a single dictionary lookup or deletion. (Backed by a SQL database with a B-tree primary-key index onid, each lookup/update/delete takesO(log N)index traversal.) - Space:
O(N)total memory across the store to holdNitem records, andO(B)temporary per-request memory to allocate a shallow response copy of the single item being created, read, or updated.
Edge cases
- Optional field omitted on
PUT: BecausePUTreplaces the whole item via_make_item, omittingdescriptionresetsdescriptiontoNoneinstead of keeping the old string. - Invalid body sent to a nonexistent
item_id:parse_item_in(payload)runs beforeif item_id not in store.items, raising422rather than404just as FastAPI does. "id"or misspelled field inside the JSON body: Rejected with422(extra="forbid"), preventing body-vs-path ID mismatches.- Boolean passed as
price({"price": true}): In Pythonboolsubclassesint(isinstance(True, int)isTrue), so checkingisinstance(price, bool)first properly rejects booleans with422. priceof0, negative numbers, orNaN: Writingnot price > 0rejects0, negatives, andfloat("nan")in one check.- IDs after deletion: Deleting the latest item does not decrement
next_id, preventing stale links to deleted/items/2from accidentally reading a newly created item. - Caller mutating the returned dictionary: Returning
dict(item)creates a defensive copy so caller edits cannot corruptstore.items.
Common mistakes
- Returning HTTP
200withnullor{"error": ...}for missing items: Breaks REST clients and HTTP caches; missing resources on/items/{id}belong to404 Not Found. - Including a JSON body on
204 No Content: The HTTP specification forbids a message body on204responses; returnResponse(status_code=204)(or-> Nonewithstatus_code=204) in FastAPI. - Accidentally implementing upsert on
PUT: Assigningstore.items[item_id] = ...without checkingif item_id not in store.itemslets clients create arbitrary IDs that collide withnext_id. - Catching broad
Exceptionand returning400or200: Hides real server bugs (500 Internal Server Error) from logs and alerting; only translate expected client mistakes into4xxHTTPExceptions. - Duplicating validation logic by hand inside
update_item: Always reuse the sharedItemInPydantic model soPOSTandPUTnever drift out of sync. - Sharing one global
ItemStoreacross unit tests: Causes order-dependent test failures; overrideDepends(get_store)in a test fixture so every test gets an isolated store.
Alternative approaches
DELETEreturning204even when already deleted: Some APIs choose "ensure absent -> always204" so network retries never see a404, trading off the ability to tell clients that they passed a mistyped ID; here the prompt explicitly distinguishes404vs204.- Service / repository layer separation: Keeping business logic in plain Python functions (
create_item,update_item, ...) and keeping@app.put(...)routes as thin 3-line HTTP adapters—just like our sandbox structure—lets unit tests verify edge cases in milliseconds without spinning up an ASGI transport.
Follow-up questions
- How would you design a
PATCH /items/{item_id}handler that supports partial field updates without breaking validation? Define a dedicatedItemPatchPydantic model withextra="forbid"where every field defaults toNone(name: Optional[str] = Field(default=None, min_length=1, max_length=100),price: Optional[float] = Field(default=None, gt=0),description: Optional[str] = Field(default=None, max_length=500)). Inside the endpoint, callchanges = patch.model_dump(exclude_unset=True)—which distinguishes "field was omitted" from "field was explicitly sent asnull"—merge{**stored.model_dump(), **changes}, and validate the merged dictionary withItem.model_validate(...), catching Pydantic'sValidationErrorto raiseHTTPException(status_code=422, detail=exc.errors())if a client explicitly sent{"name": null}or{"price": null}. - What race condition arises when two clients send
PUT /items/1at the same time, and how can you prevent lost updates? With unconditionalPUT, the second request overwrites the first silently (last-write-wins). To prevent lost updates, use optimistic concurrency control: attach an integerversion(or HTTPETagheader) to everyItem, requirePUTcallers to pass the version they read in anIf-Matchheader, and return412 Precondition Failedwhenever the stored version has moved ahead. Also remember that FastAPI runs synchronousdefendpoints on a worker thread pool, so an in-memoryItemStoremust guardnext_id += 1and dictionary updates with athreading.Lock(or rely on database row locks andSERIAL/IDENTITYsequences in production). - How would you swap the in-memory
ItemStorefor a PostgreSQL database while keeping unit tests fast and isolated? Replaceget_storewith a generator dependencyget_db()that yields a SQLAlchemySession(or async session) inside atry ... finally: db.close()block.read_itemandupdate_itemlook up the row via primary key (db.get(ItemRow, item_id)->404ifNone), whiledelete_itemdeletes the row and commits (raising404if 0 rows matched). Inpytest, pointapp.dependency_overrides[get_db]at a test database session wrapped in an outer transaction that rolls back after every test, giving each test a clean database in milliseconds.
Follow-up questions
- How would you design a `PATCH /items/{item_id}` handler that supports partial field updates without breaking validation?
- What race condition arises when two clients send `PUT /items/1` at the same time, and how can you prevent lost updates?
- How would you swap the in-memory `ItemStore` for a PostgreSQL database while keeping unit tests fast and isolated?
Similar questions
- Incremental Number-Triangle Rows
- ML Engineer Pitch, Startup Motivation, and API Contracts
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging