KatInterview

Finish a REST Resource: Update and Delete Routes in FastAPI

Data Structure DesignModel answer
MediumModel answerData Structure Designfastapirest-apipydantic

Last 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

  1. 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.
  2. 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).
  3. Validate and handle errors.
    • Reject malformed bodies and invalid ids.
    • Handle storage-level failures in one place rather than scattering try/except blocks through the routes.
  4. Test everything. Write unit tests covering all four operations: success paths, missing records, invalid input and idempotent repeats.
  5. 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).