Problem statement
Build the conversion that turns the inventory's out of stock failure into a 409 answer of its own, registered once on the application so every endpoint that takes stock shares it, while every other failure keeps the answer it already had.
Sample Data
The catalogue in app/store.py holds three products: usb-c-cable with a stock of 2_, _hdmi-adapter with 6_ and _laptop-stand with 0.
API Endpoints to Implement
register_error_handlers in app/errors.py is handed the application. Register the conversion there, on the application itself, so it is not written into any endpoint.
- take_stock in app/services/inventory.py raises OutOfStockError when more is asked for than the stock holds. It carries sku, requested and available.
- That failure is answered with 409, a content type of application/json, and a body holding exactly error, always the text out_of_stock, then sku, requested and available taken from the failure.
- POST /orders and POST /reservations both take stock, and both share the one conversion without either of them handling the failure.
- Every other failure keeps the answer it already had. A report failure and an unknown sku both stay on the default 500, a content type of text/plain and the body Internal Server Error. A body missing a required field stays on the default 422, with one detail entry per absent field carrying loc of ["body", "sku"] or ["body", "quantity"], an input of the body that was sent, and the type and msg reported for the rule.
Sample Requests & Responses
POST /orders
Request:
{
"sku": "usb-c-cable",
"quantity": 5
}
Response (409 Conflict):
{
"error": "out_of_stock",
"sku": "usb-c-cable",
"requested": 5,
"available": 2
}
POST /reservations
Request:
{
"sku": "laptop-stand",
"quantity": 1
}
Response (409 Conflict):
{
"error": "out_of_stock",
"sku": "laptop-stand",
"requested": 1,
"available": 0
}
GET /reports/latest
Response (500 Internal Server Error), a text/plain body of Internal Server Error.
POST /orders
Request:
{
"sku": "usb-c-cable"
}
Response (422 Unprocessable Entity):
{
"detail": [
{
"type": "missing",
"loc": ["body", "quantity"],
"msg": "Field required",
"input": {"sku": "usb-c-cable"}
}
]
}
