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) — mirrors fastapi.HTTPException, representing an HTTP error response (status_code, {"detail": detail}).
  • parse_item_in(payload: Any) -> Dict[str, Any] — mirrors a shared ItemIn Pydantic request model and raises HTTPException(422, ...) on any schema violation.
  • ItemStore — an injected in-memory store holding items: Dict[int, Dict[str, Any]] and an auto-incrementing next_id: int starting at 1.
  • Two completed handlers:
    • create_item(store: ItemStore, payload: Any) -> Tuple[int, Dict[str, Any]] (POST /items -> 201 with a shallow copy of the stored item, or 422).
    • read_item(store: ItemStore, item_id: int) -> Tuple[int, Dict[str, Any]] (GET /items/{item_id} -> 200 with a shallow copy of the stored item, or 404).

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:

  1. update_item (PUT /items/{item_id}):
    • Validate payload via parse_item_in(payload) before checking whether item_id exists in store.items, so invalid payloads raise HTTPException(422, ...) even when item_id is absent (matching FastAPI's schema-first pipeline).
    • If item_id is not present in store.items, raise HTTPException(404, "Item not found") without inserting anything or modifying store.next_id.
    • Perform a full replacement of store.items[item_id] keeping "id": item_id from the URL path (any omitted optional "description" resets to None), and return (200, copy_of_record) as a shallow copy so caller edits cannot mutate stored data. Sending the same valid PUT repeatedly must be idempotent.
  2. delete_item (DELETE /items/{item_id}):
    • If item_id is not in store.items, raise HTTPException(404, "Item not found").
    • Otherwise delete store.items[item_id] without decrementing store.next_id (deleted IDs are never recycled) and return (204, None) (204 No Content). Repeating DELETE on an already-deleted ID raises HTTPException(404, "Item not found") while leaving stored state unchanged.

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

  • payload for POST and PUT must be a dict containing only keys in ("name", "price", "description"); unknown keys (including "id") raise HTTPException(422, ...).
  • name: required str with 1 <= len(name) <= 100.
  • price: required int or float (not bool) strictly greater than 0, stored as float.
  • description: optional (None when omitted) or str with len(description) <= 500.
  • Returned item dictionaries from create_item, read_item, and update_item must be copies disconnected from store.items.

Step-by-step walkthrough

  1. 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 endpoint
    

    Three 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 that update_item is simply create's body validation + read's 404 check, and delete_item is read's 404 check + removal!

  2. 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 id
    

    Three REST rules govern PUT and DELETE here: - PUT replaces the entire resource: Omitting an optional field like description resets it to its default (None), rather than keeping the old description (partial field-by-field updates belong to PATCH). - PUT does not create new IDs: Because POST owns ID generation (1, 2, 3, ...), sending PUT /items/999 for a missing ID must return 404 Not Found rather than silently creating item 999. - 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)
    
  3. 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 JSON
    

    Two 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 with extra="forbid": Reusing ItemIn for both POST and PUT guarantees identical rules, and forbidding unknown fields rejects bodies containing "id": 9 so the item's ID can only ever come from the URL path.

  4. 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, and ItemStore, alongside the two working create_item and read_item functions:

    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)
    
  5. Implement update_item (PUT /items/{item_id})

    Combine the exact pieces from create_item and read_item in order: 1. Validate payload with parse_item_in(payload) first (422 on invalid input, even if item_id does not exist). 2. Check if item_id not in store.items: and raise HTTPException(404, "Item not found"). 3. Build a brand-new dictionary via _make_item(item_id, fields)—ensuring omitted optional fields reset cleanly to None—store it at store.items[item_id] without touching store.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)
    
  6. Implement delete_item (DELETE /items/{item_id})

    Check existence just like read_item, remove the item from store.items, leave store.next_id unchanged so old deleted IDs are never recycled onto future items, and return (204, None) to represent HTTP 204 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, None
    
  7. Map the endpoints and isolated unit tests to real FastAPI

    In a real FastAPI codebase, parse_item_in becomes the shared ItemIn Pydantic model, and update_item / delete_item sit right beside @app.post and @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, override app.dependency_overrides[get_store] inside a pytest fixture so every test starts with a fresh ItemStore and 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()
    
  8. 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) per create_item and update_item request to inspect the keys and string lengths of the incoming payload plus O(1) average time to look up or assign store.items[item_id]; O(1) average time per read_item and delete_item request for a single dictionary lookup or deletion. (Backed by a SQL database with a B-tree primary-key index on id, each lookup/update/delete takes O(log N) index traversal.)
  • Space: O(N) total memory across the store to hold N item records, and O(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: Because PUT replaces the whole item via _make_item, omitting description resets description to None instead of keeping the old string.
  • Invalid body sent to a nonexistent item_id: parse_item_in(payload) runs before if item_id not in store.items, raising 422 rather than 404 just as FastAPI does.
  • "id" or misspelled field inside the JSON body: Rejected with 422 (extra="forbid"), preventing body-vs-path ID mismatches.
  • Boolean passed as price ({"price": true}): In Python bool subclasses int (isinstance(True, int) is True), so checking isinstance(price, bool) first properly rejects booleans with 422.
  • price of 0, negative numbers, or NaN: Writing not price > 0 rejects 0, negatives, and float("nan") in one check.
  • IDs after deletion: Deleting the latest item does not decrement next_id, preventing stale links to deleted /items/2 from accidentally reading a newly created item.
  • Caller mutating the returned dictionary: Returning dict(item) creates a defensive copy so caller edits cannot corrupt store.items.

Common mistakes

  • Returning HTTP 200 with null or {"error": ...} for missing items: Breaks REST clients and HTTP caches; missing resources on /items/{id} belong to 404 Not Found.
  • Including a JSON body on 204 No Content: The HTTP specification forbids a message body on 204 responses; return Response(status_code=204) (or -> None with status_code=204) in FastAPI.
  • Accidentally implementing upsert on PUT: Assigning store.items[item_id] = ... without checking if item_id not in store.items lets clients create arbitrary IDs that collide with next_id.
  • Catching broad Exception and returning 400 or 200: Hides real server bugs (500 Internal Server Error) from logs and alerting; only translate expected client mistakes into 4xx HTTPExceptions.
  • Duplicating validation logic by hand inside update_item: Always reuse the shared ItemIn Pydantic model so POST and PUT never drift out of sync.
  • Sharing one global ItemStore across unit tests: Causes order-dependent test failures; override Depends(get_store) in a test fixture so every test gets an isolated store.

Alternative approaches

  • DELETE returning 204 even when already deleted: Some APIs choose "ensure absent -> always 204" so network retries never see a 404, trading off the ability to tell clients that they passed a mistyped ID; here the prompt explicitly distinguishes 404 vs 204.
  • 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 dedicated ItemPatch Pydantic model with extra="forbid" where every field defaults to None (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, call changes = patch.model_dump(exclude_unset=True)—which distinguishes "field was omitted" from "field was explicitly sent as null"—merge {**stored.model_dump(), **changes}, and validate the merged dictionary with Item.model_validate(...), catching Pydantic's ValidationError to raise HTTPException(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/1 at the same time, and how can you prevent lost updates? With unconditional PUT, the second request overwrites the first silently (last-write-wins). To prevent lost updates, use optimistic concurrency control: attach an integer version (or HTTP ETag header) to every Item, require PUT callers to pass the version they read in an If-Match header, and return 412 Precondition Failed whenever the stored version has moved ahead. Also remember that FastAPI runs synchronous def endpoints on a worker thread pool, so an in-memory ItemStore must guard next_id += 1 and dictionary updates with a threading.Lock (or rely on database row locks and SERIAL/IDENTITY sequences in production).
  • How would you swap the in-memory ItemStore for a PostgreSQL database while keeping unit tests fast and isolated? Replace get_store with a generator dependency get_db() that yields a SQLAlchemy Session (or async session) inside a try ... finally: db.close() block. read_item and update_item look up the row via primary key (db.get(ItemRow, item_id) -> 404 if None), while delete_item deletes the row and commits (raising 404 if 0 rows matched). In pytest, point app.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

Similar questions

More Credit Genie interview questions

All 3 Credit Genie questions →