Custom Flask-RESTful routes except GET, PUT, POST, DELETE

In Flask-RESTful, we add an api route as shown below

api.add_resource(CuteKitty,'/api/kitty') class CuteKitty(Resource): def get(self): return {} def post(self): return {} def put(self): return {} def delete(self): return None, 204 

so that the method GET /api/kitty → to CuteKitty.get() ; like this for all http verbs

Let's say I need to provide my api consumers with a nice api like

 POST /api/kitty/drink/milk ---> CuteKitty.drink(what="milk") POST /api/kitty/meow ---> CuteKitty.meow() 

How can I achieve the above routing using api.add_resource

 class CuteKitty(Resource): def get(self): return {} def post(self): return {} def put(self): return {} def delete(self): return None, 204 def drink(self,what="milk"): return {} def meow(self): return {} 

As a wise way to add a route, e.g. /api/kitty/<int:kitty_id>/habits CuteKitty.habits(kitty_id)

+5
source share
1 answer

Flask-RESTful is intended to implement the RESTful API, in particular by interpreting the HTTP request method. Drink and Meow, obviously, are not HTTP methods (at least they are not specified in the specification - I will leave this at the same time), Flask-RESTful is not connected with the drink and meow in the resource.

The obvious answer to this is to define several API routes:

 api.add_resource(CuteKitty, '/kitty/<int:kitty_id>/') api.add_resource(DrinkingKitty, '/kitty/<int:kitty_id>/drink/<what>') api.add_resource(MeowingKitty, '/kitty/<int:kitty_id>/meow/') 

A less obvious way is to create a frankenresource:

 # still allow requests to hit just get/post/etc without invoking anything else api.add_resource(CuteKitty, '/kitty/<int:kitty_id>/') api.add_resource(CuteKitty, '/kitty/<int:kitty_id>/<task>/<path:args>/') 

And then break the arguments with split('/') and invoke the task with them. Alternatively, you can set them as URL arguments ( /endpoint/?task=drink&what=milk ) - this is still a valid RESTful architecture.

You can also subclass the resource class and implement the desired functionality yourself - in this case, I would recommend to see how Flask-Classy implements this. Or you can pick up Flask-Classy and play with it and see how you like it; however, for the direct API, I believe that RESTful brings a lot more than Classy.

+5
source

Source: https://habr.com/ru/post/1202211/


All Articles