Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-RESTful custom routes other than GET,PUT,POST,DELETE

In Flask-RESTful we add an api route like the 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 GET /api/kitty --> to CuteKitty.get() method; like this for all HTTP verbs

Lets say that I need to provide my api consumers with a cute api like

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

How can i achive the above routing with 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 {}

Like wise how to add route like /api/kitty/<int:kitty_id>/habits --> CuteKitty.habits(kitty_id)

like image 578
cackharot Avatar asked Sep 10 '14 05:09

cackharot


2 Answers

Flask-RESTful is designed to implement RESTful APIs specifically by interpreting the HTTP Request method. Drink and Meow are not standard HTTP methods so Flask-RESTful isn't concerned with the drink and meow methods in the resource.

The solution to this is to define multiple 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/')

The less intuitive (and imo far worse) way is by creating 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 args with split('/') and call task with them. Alternatively, you could set these as URL arguments (/endpoint/?task=drink&what=milk) -- which is still a valid RESTful architecture.

You could also subclass the Resource class and implement the desired functionality yourself -- in this case, I'd recommend looking at how Flask-Classy implements this. Or you could pick up Flask-Classy and toy with it and see how you like that, too; however, for a straight up API I think RESTful brings a lot more to the table than Classy.

like image 141
justanr Avatar answered Oct 14 '22 20:10

justanr


Step 1: Write the Resource class.

class CuteKitty(Resource):
   def get(self): return {}
   def post(self): return {}
   def put(self): return {}
   def delete(self): return None, 204
   def meow(self): return {}

Step 2: Below the class, or after obtaining the callable,

api.add_resource(CuteKitty,'/api/kitty/meow',endpoint='meow',methods=['GET'])
like image 3
Henshal B Avatar answered Oct 14 '22 22:10

Henshal B