p2k: add Routing & Sub-routers tutorial — route decorators, APIRouter, tags, middleware, ordering

swadhinbiswas committed 3 months ago
707cadd
1 parent 8dac5ad
commit 707cadd
1 file changed
+151 -0
▼docs_site/src/content/docs/tutorials/routing-subrouters.md
+151-0
1
+---
2
+title: Routing & Sub-routers
3
+description: Organize your API with modular routers and route groups.
4
+---
5
+
6
+JustAPI's routing system uses a radix-trie (via `matchit`) for O(1) route matching. Routes are registered with decorators and can be organized across multiple files using `APIRouter`.
7
+
8
+## HTTP Method Decorators
9
+
10
+```python
11
+from justapi import JustAPIApp
12
+
13
+app = JustAPIApp()
14
+
15
+
16
+@app.get("/users")
17
+def list_users(request):
18
+ return [{"id": 1, "name": "Alice"}]
19
+
20
+
21
+@app.post("/users")
22
+def create_user(request):
23
+ return {"message": "User created"}
24
+
25
+
26
+@app.put("/users/{user_id}")
27
+def update_user(request, user_id: int):
28
+ return {"user_id": user_id, "updated": True}
29
+
30
+
31
+@app.patch("/users/{user_id}")
32
+def patch_user(request, user_id: int):
33
+ return {"user_id": user_id, "patched": True}
34
+
35
+
36
+@app.delete("/users/{user_id}")
37
+def delete_user(request, user_id: int):
38
+ return {"deleted": user_id}
39
+```
40
+
41
+## Using `APIRouter` for Modular Routes
42
+
43
+Group related routes in separate files:
44
+
45
+```python
46
+# app/routers/products.py
47
+from justapi import APIRouter
48
+
49
+router = APIRouter(prefix="/products", tags=["Products"])
50
+
51
+
52
+@router.get("/")
53
+def list_products(request):
54
+ return [{"id": 1, "name": "Rust Book"}]
55
+
56
+
57
+@router.get("/{product_id}")
58
+def get_product(request, product_id: int):
59
+ return {"product_id": product_id, "name": f"Product {product_id}"}
60
+```
61
+
62
+```python
63
+# app/routers/reviews.py
64
+from justapi import APIRouter
65
+
66
+router = APIRouter(prefix="/products/{product_id}/reviews", tags=["Reviews"])
67
+
68
+
69
+@router.get("/")
70
+def list_reviews(request, product_id: int):
71
+ return [{"id": 1, "product_id": product_id, "rating": 5}]
72
+```
73
+
74
+```python
75
+# app/main.py
76
+from justapi import JustAPIApp
77
+from app.routers.products import router as products_router
78
+from app.routers.reviews import router as reviews_router
79
+
80
+app = JustAPIApp()
81
+app.include_router(products_router)
82
+app.include_router(reviews_router)
83
+```
84
+
85
+## Route with Tags
86
+
87
+Tags group endpoints in the auto-generated OpenAPI documentation:
88
+
89
+```python
90
+@router.get("/", tags=["Products"])
91
+def list_products(request):
92
+ ...
93
+```
94
+
95
+## Router-Level Middleware
96
+
97
+```python
98
+from justapi import APIRouter, Depends, HTTPException, Header
99
+
100
+admin_router = APIRouter(prefix="/admin", tags=["Admin"])
101
+
102
+
103
+def require_admin(authorization: str = Header(...)):
104
+ if authorization != "Bearer admin-token":
105
+ raise HTTPException(403, "Admin access required")
106
+
107
+
108
+@admin_router.get("/users", dependencies=[Depends(require_admin)])
109
+def list_all_users(request):
110
+ return [{"id": 1, "name": "Alice"}]
111
+
112
+
113
+app.include_router(admin_router)
114
+```
115
+
116
+## Route Ordering
117
+
118
+Routes are matched in the order they are registered. More specific routes should come before parameterized routes:
119
+
120
+```python
121
+# Specific route first
122
+@app.get("/users/me")
123
+def get_current_user(request):
124
+ return {"user": "current"}
125
+
126
+# Parameterized route second
127
+@app.get("/users/{user_id}")
128
+def get_user(request, user_id: int):
129
+ return {"user_id": user_id}
130
+```
131
+
132
+## Route-Lookup Cache
133
+
134
+For high-traffic routes, JustAPI caches route lookups in a memoization table (ADR-064). This avoids radix-trie traversal on repeated requests to the same path.
135
+
136
+## OpenAPI Documentation
137
+
138
+All registered routes are automatically documented:
139
+
140
+| URL | Description |
141
+|---|---|
142
+| `/docs` | Swagger UI |
143
+| `/redoc` | ReDoc |
144
+| `/scalar` | Scalar API Reference |
145
+| `/openapi.json` | Raw OpenAPI 3.1 spec |
146
+
147
+## Next Steps
148
+
149
+- [API Reference: Routing](/api-reference/routing/) — Complete routing API
150
+- [API Reference: APIRouter](/api-reference/apirouter/) — Router reference
151
+- [Multi-Protocol APIs](/advanced/multi-protocol-apis/) — REST, GraphQL, gRPC, JSON-RPC
0
152