Routing & Controllers: Handling Dynamic Data in URLs
Source: Dev.to
What are Dynamic Routes?
Static routes like /about always return the same thing.
Dynamic routes allow the URL to contain variable parts, enabling APIs to serve different resources with a single endpoint pattern, e.g., /user/1 and /user/2.
@app.get("/user/{user_id}")
def get_user(user_id: int):
return {
"user_id": user_id,
"message": f"Fetching user with ID {user_id}"
}
@app.get("/product/{product_name}")
def get_product(product_name: str):
return {
"product": product_name,
"message": f"Fetching product: {product_name}"
}
@app.get("/user/{user_id}/order/{order_id}")
def get_user_order(user_id: int, order_id: int):
return {
"user_id": user_id,
"order_id": order_id,
"message": f"Order {order_id} for user {user_id}"
}
Calling /user/1/order/42 tells you exactly which resource is being requested: the order with ID 42 for the user with ID 1.
Dynamic routing is what makes APIs actually useful.