| 1 |
from dataclasses import dataclass |
| 2 |
|
| 3 |
from litestar import Litestar, post |
| 4 |
from litestar.plugins.problem_details import ProblemDetailsConfig, ProblemDetailsException, ProblemDetailsPlugin |
| 5 |
|
| 6 |
|
| 7 |
@dataclass |
| 8 |
class PurchaseItem: |
| 9 |
item_id: int |
| 10 |
quantity: int |
| 11 |
|
| 12 |
|
| 13 |
@post("/purchase") |
| 14 |
async def purchase(data: PurchaseItem) -> None: |
| 15 |
# Logic to check if the user has enough credit to buy the item. |
| 16 |
# We assume the user does not have enough credit. |
| 17 |
|
| 18 |
raise ProblemDetailsException( |
| 19 |
type_="https://example.com/probs/out-of-credit", |
| 20 |
title="You do not have enough credit.", |
| 21 |
detail="Your current balance is 30, but that costs 50.", |
| 22 |
instance="/account/12345/msgs/abc", |
| 23 |
extra={"balance": 30}, |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
problem_details_plugin = ProblemDetailsPlugin(ProblemDetailsConfig()) |
| 28 |
app = Litestar(route_handlers=[purchase], plugins=[problem_details_plugin]) |
| 29 |
|
| 30 |
# run: /purchase --header "Content-Type: application/json" --request POST --data '{"item_id": 1234, "quantity": 2}' |