REST Routing Without External Frameworks
Frameworks like Flask or FastAPI are built around routing registries. You can build your own decorator-based router in 10 lines of pure Python using a URL dictionary mapping 🛣️.
routes = {}
def route(path):
def decorator(func):
routes[path] = func
return func
return decorator
@route("/api/ping")
def ping():
return {"message": "pong"}
@route("/api/users")
def users():
return [{"id": 1, "name": "ada"}]
print(f"Dispatched /api/ping: {routes['/api/ping']()} 🛣️")
# 38. REST Routing Without External Frameworks Frameworks like Flask or FastAPI are built around routing registries. You can build your own decorator-based router in 10 lines of pure Python using a URL dictionary mapping 🛣️. ```python routes = {} def route(path): def decorator(func): routes[path] = func return func return decorator @route("/api/ping") def ping(): return {"message": "pong"} @route("/api/users") def users(): return [{"id": 1, "name": "ada"}] print(f"Dispatched /api/ping: {routes['/api/ping']()} 🛣️") ``` Demystifying routing helps you see that all modern web frameworks are simply dictionary lookups wrapped in exception handlers! 🛣️ --- ### Question How does a decorator-based router like `@route('/api')` map incoming URLs to controller functions? 🧠 - [ ] a. Registers the URL path as a key in a dictionary mapping to the function object 🛣️ - [ ] b. Recompiles the Linux network routing table - [ ] c. Creates a new thread for each URL in memory - [ ] d. Executes the function immediately upon import --- ### Challenge Create a router dictionary `routes = {}` and decorator `get(path)`. Decorate `def health(): return "OK"`. Dispatch `routes["/health"]()` and print the result. 🎯 <details> <summary>Solution</summary> ```python routes = {} def get(path): def dec(fn): routes[path] = fn return fn return dec @get("/health") def health(): return "OK" print(routes["/health"]()) ``` </details>