Finish a REST Resource: Update and Delete Routes in FastAPI
Data Structure DesignModel answerLast updated
Extend a small FastAPI service with replace and remove routes that follow existing conventions, handle idempotency and errors correctly, and ship with a full test suite.
You inherit a small FastAPI service that manages a single resource type. Two routes already work: one that creates a record and one that fetches a record by id. Both share Pydantic models for input and output, and they get their storage through dependency injection.
Your job is to finish the resource by adding the two missing operations: replace and remove.
Requirements
- Stay consistent. The new routes must use the same request and response schemas, the same style of dependency injection, and the same status-code and error conventions as the existing ones.
- Respect HTTP semantics.
- Replacing and removing must both be idempotent in terms of server state.
- Distinguish a missing record (
404) from a successful removal (204).
- Validate and handle errors.
- Reject malformed bodies and invalid ids.
- Handle storage-level failures in one place rather than scattering
try/exceptblocks through the routes.
- Test everything. Write unit tests covering all four operations: success paths, missing records, invalid input and idempotent repeats.
- Explain your process. Describe how you would tackle this task if you had never used FastAPI before, using the existing routes as templates and the official documentation as a reference.
Assume the skeleton follows a typical layout: a base model, a create model, a response model that adds an id, and a store object returned by a get_store dependency. If the real code differs (for example, it uses partial updates), say so and match it.
Hints
Hint 1
Read the two existing routes first and list what they decide: path style, response_model, status_code, how the store is injected, and how a missing record is reported. Your new routes should copy each of those decisions.
Hint 2
Idempotency concerns server state, not identical responses. Replacing with the same body twice leaves the same state, and deleting twice leaves the item gone, even though the second delete returns 404.
Hint 3
For tests, override the store dependency with a fresh instance per test so tests are isolated, and use parametrize to cover the many invalid-input cases (empty name, negative price, missing field, unknown field, id of 0 or non-numeric).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is mostly about reading an existing codebase and matching it, then making sound HTTP decisions and proving them with tests. I would say up front: "I'll mirror the create and read routes for schemas, dependency injection and error style, then fill in replace and remove."
Assumed skeleton
- Models:
ItemBase(with field constraints),ItemCreate, andItem(addsid). - Storage: a store object injected via
Depends(get_store). - Errors:
HTTPException(404)for a missing record.
Design decisions
Replace: PUT /items/{item_id}
- Full replacement, so the body uses the same rules as create (an
ItemUpdatethat subclasses the base). - Returns
200with theItemschema, or404if the id does not exist. - PUT is idempotent: the same body sent twice yields the same state and the same response.
- Note that PUT should not create a missing item here, because the spec asks for 404. If the existing code used PATCH semantics, I would match that instead.
Remove: DELETE /items/{item_id}
204 No Contentwith an empty body if the item existed,404otherwise.- This is still idempotent. Idempotency means repeated calls leave the server in the same state, not that they return the same status. After the first call the item is gone and later calls change nothing.
- Some teams prefer "always 204". I would mention the trade-off (simpler clients and retries versus losing the signal that the id was wrong) but follow the spec.
Validation
- Field constraints (
min_length,ge=0,max_length) andextra="forbid"on the model reject bad bodies. Path(gt=0)rejects bad ids.- FastAPI turns both into
422automatically, so no manual checks are needed.
Exception handling
- Domain failures, such as a storage outage, raise a custom
StorageError. - One registered
exception_handlermaps it to503. Route code stays small and every route behaves the same way.
Concurrency
- A lock around mutations in the store keeps replace and delete atomic. The check-then-write must happen inside the lock, otherwise two requests can interleave. With a real database, use a single
UPDATE ... WHERE id = ?orDELETE ... WHERE id = ?and check the affected row count.
Implementation
from typing import Annotated, Optional
from fastapi import Depends, FastAPI, HTTPException, Path, Request, Response, status
from fastapi.responses import JSONResponse
ItemId = Annotated[int, Path(gt=0)]
Store = Annotated[ItemStore, Depends(get_store)]
@app.exception_handler(StorageError)
async def storage_error_handler(request: Request, exc: StorageError):
return JSONResponse(status_code=503, content={"detail": "Storage unavailable"})
@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: ItemId, payload: ItemUpdate, store: Store) -> Item:
item = store.replace(item_id, payload) # returns None if missing
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: ItemId, store: Store) -> Response:
if not store.delete(item_id): # returns bool
raise HTTPException(status_code=404, detail="Item not found")
return Response(status_code=status.HTTP_204_NO_CONTENT)
The store methods do the existence check and the write under one lock:
def replace(self, item_id, data):
with self._lock:
if item_id not in self._items:
return None
item = Item(id=item_id, **data.model_dump())
self._items[item_id] = item
return item
def delete(self, item_id):
with self._lock:
return self._items.pop(item_id, None) is not None
Returning an explicit Response for 204 matters. If a handler returns a body with a 204, the framework and clients may complain about content on a no-content response.
Tests
Use a fixture that builds a fresh store per test and installs it with app.dependency_overrides[get_store], then clears the override afterwards.
- Create:
201and the returned body; parametrized422cases (empty name, negative price, missing field, extra field). - Read: existing returns
200; unknown id returns404; id0orabcreturns422. - Update:
- Replaces the stored data, and a follow-up GET shows the new values.
- Sending the same PUT twice gives the same status and body (idempotency).
- Unknown id returns
404; invalid body returns422. - Omitted optional fields reset to defaults, which proves full-replacement semantics.
- Delete:
- First call returns
204with an empty body. - A follow-up GET returns
404. - Second delete returns
404while state is unchanged. - Invalid id returns
422.
- First call returns
- Errors: override the store with one that raises
StorageErrorand assert503with the expected detail.
If I had never used FastAPI
- Run the app and open the auto-generated
/docspage to see the existing routes and schemas live. - Read the create and read routes line by line, and look up each unfamiliar piece (
Depends,Path,response_model,status_code) in the official docs. - Copy the nearest existing route, change one thing at a time, and use
/docsor aTestClientcall to check the result. - Read the docs sections on request bodies, handling errors, and testing with dependency overrides, which are the three areas this task touches.
- Write the tests early, starting by copying the style of any existing tests.
Common mistakes
- Returning
200with a body from DELETE, or a body with 204. - Making DELETE return
200/204for a missing id when the spec says404. - Defining a new update model with looser rules than create, so PUT accepts data that POST rejects.
- Doing the existence check and the write as separate unlocked steps.
- Sharing global store state between tests, which makes ids and results order-dependent.
- Confusing idempotent with "returns the same status code".
- Wrapping every route in its own
try/exceptinstead of using a registered exception handler.
Complexity
Each operation is O(1) against the in-memory dict. With a database, it is a single indexed primary-key statement.