pythonroutesnested-resourcesflask-restfulnested-routes

Is there a way to configure routes hierarchy in Python Flask-RESTFUL?


So let's say I have a few routes:

api.add_resource(Customers, "/Customers")
api.add_resource(Customer, "/Customer/<int:customerId>")

Now, the customer can have many things associated with it. Say for example, orders:

api.add_resource(Customers, "/Customers")
api.add_resource(Customer, "/Customer/<int:customerId>")
api.add_resource(Orders, "/Customer/<int:customerId>/Orders")
api.add_resource(Order, "/Customer/<int:customerId>/Order/<int:orderId>")

Is there any way to get around repeating the "/Customer/< int:customerId>" section? It seems redundant and prone to typos.

Say we throw in, shopping cart, likes, previously viewed, wishlist, support tickets, etc... We can easily repeat that information over and over.

Not to mention any resource an order might have on its own. Now we're repeating customer and order route information.

Is there any way to set up a hierarchy of some sort to say:

api.add_resourceToPrevious([oldRoute], [newRouteController], [newRouteToAppendToOld])

Solution

  • It doesn't appear that flask has a built-in way to do that. However, you can still use Python features:

    customer_path = '/Customer/<int:customerID>'
    api.add_resource(Customer, customer_path)
    api.add_resource(Orders, customer_path + '/Orders')
    api.add_resource(Order, customer_path + '/Order/<int:orderId>')