Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
178 lines (127 loc) · 6.13 KB
/
Copy pathapp.py
File metadata and controls
178 lines (127 loc) · 6.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""FastAPI Product Inventory API with FlowDoc decorators on endpoints.
Demonstrates how ``@step`` works directly alongside FastAPI's route
decorators. FlowDoc discovers the business flow by analysing which
``@step``-decorated functions call other ``@step``-decorated functions.
Usage:
uvicorn examples.fastapi.app:app --reload
Generate diagrams:
flowdoc generate examples/fastapi/app.py --format png
flowdoc generate examples/fastapi/app.py --format mermaid
"""
from __future__ import annotations
from dataclasses import asdict, dataclass
from flowdoc import step
try:
from fastapi import FastAPI, HTTPException, Query
except ImportError as exc:
raise SystemExit(
"FastAPI is required to run this example: pip install fastapi uvicorn"
) from exc
app = FastAPI(
title="Product Inventory API",
description="CRUD API for product catalog management — powered by FlowDoc",
version="1.0.0",
)
# ── Models ──────────────────────────────────────────────────────────
@dataclass
class CreateProductRequest:
"""Request payload for creating a product."""
name: str
sku: str
price: float
stock: int
category: str
@dataclass
class UpdateProductRequest:
"""Request payload for updating a product."""
name: str | None = None
price: float | None = None
stock: int | None = None
category: str | None = None
# ── Helper steps ────────────────────────────────────────────────────
@step(name="Validate Product Data", description="Check required fields and value ranges")
def validate_product_data(data: dict) -> dict:
errors: list[str] = []
if not data.get("name"):
errors.append("name is required")
if not data.get("sku"):
errors.append("sku is required")
if data.get("price", 0) <= 0:
errors.append("price must be positive")
return {"valid": len(errors) == 0, "errors": errors, "data": data}
@step(name="Check Duplicate SKU", description="Ensure SKU is unique in catalog")
def check_duplicate_sku(sku: str) -> bool:
# Placeholder — would query the database in production
return False
@step(name="Save Product", description="Persist new product to the database")
def save_product(data: dict) -> dict:
return notify_catalog_update({"id": "prod_123", **data})
@step(name="Notify Catalog Update", description="Publish event for downstream systems")
def notify_catalog_update(product: dict) -> dict:
# Placeholder — would publish to an event bus in production
return product
@step(name="Lookup Product", description="Query database for a product by ID")
def lookup_product(product_id: str) -> dict | None:
# Placeholder — would query the database in production
return None
@step(name="Apply Update", description="Merge changes and persist to database")
def apply_update(product_id: str, updates: dict) -> dict:
return notify_catalog_update({"id": product_id, **updates})
@step(name="Check Order References", description="Look for active orders referencing this product")
def check_order_references(product_id: str) -> bool:
# Placeholder — would query the orders table in production
return False
@step(name="Soft Delete", description="Mark product as inactive")
def soft_delete(product_id: str) -> dict:
return notify_catalog_update({"id": product_id, "action": "deactivated"})
@step(name="Hard Delete", description="Permanently remove product from database")
def hard_delete(product_id: str) -> dict:
return notify_catalog_update({"id": product_id, "action": "deleted"})
# ── Endpoints ───────────────────────────────────────────────────────
@app.post("/products", status_code=201)
@step(name="Create Product", description="Validate, de-duplicate, and persist a new product")
async def create_product(request: CreateProductRequest) -> dict:
result = validate_product_data(asdict(request))
if not result["valid"]:
raise HTTPException(status_code=422, detail=result["errors"])
is_duplicate = check_duplicate_sku(request.sku)
if is_duplicate:
raise HTTPException(status_code=409, detail="SKU already exists")
product = save_product(result["data"])
return {"status": "created", "product": product}
@app.get("/products/{product_id}")
@step(name="Get Product", description="Retrieve a single product by ID")
async def get_product(product_id: str) -> dict:
product = lookup_product(product_id)
if product is None:
raise HTTPException(status_code=404, detail="Product not found")
return {"status": "ok", "product": product}
@app.put("/products/{product_id}")
@step(name="Update Product", description="Validate and apply changes to an existing product")
async def update_product(product_id: str, request: UpdateProductRequest) -> dict:
existing = lookup_product(product_id)
if existing is None:
raise HTTPException(status_code=404, detail="Product not found")
updates = {k: v for k, v in asdict(request).items() if v is not None}
result = validate_product_data({**existing, **updates})
if not result["valid"]:
raise HTTPException(status_code=422, detail=result["errors"])
product = apply_update(product_id, updates)
return {"status": "updated", "product": product}
@app.delete("/products/{product_id}", status_code=204)
@step(name="Delete Product", description="Soft- or hard-delete depending on order references")
async def delete_product(
product_id: str,
hard: bool = Query(default=False, description="Permanently remove instead of soft-delete"),
) -> None:
existing = lookup_product(product_id)
if existing is None:
raise HTTPException(status_code=404, detail="Product not found")
has_orders = check_order_references(product_id)
if has_orders:
soft_delete(product_id)
else:
if hard:
hard_delete(product_id)
else:
soft_delete(product_id)