Chinmay Kanchi
Chinmay Kanchi

Reputation: 65853

Per-method routes on flask-restful

I'm building a RESTful API using flask-restful and have run into a small issue.

Essentially, I need to ensure that certain methods only work if a required parameter is provided, while certain others work only if a parameter is not provided.

For instance:

from flask import jsonify
from flask.ext import restful

api = restful.Api()
class TestResource(restful.Resource):
    def get(self, some_id=None):
        '''GET takes an optional parameter'''
        if some_id:
            return jsonify(something1)
        else:
            return jsonify(something2)

    def post(self):
        '''POST doesn't take any params'''
        #do stuff
        return jsonify(something3)

    def put(self, some_id):
        '''PUT has a mandatory argument'''
        #do stuff
        return jsonify(something4)

restful.add_resource(TestResource, '/testresource/', '/testresource/<string:some_id>')

Now, requests.get('http://mydomain.tld/testresource') and requests.get('http://mydomain.tld/testresource/1') will both work fine, but requests.post('http://mydomain.tld/testresource/1') will cause a Python error (TypeError: post() takes only 1 argument (2 given)), which causes flask-restful to return a HTTP 500 response.

While I can have an optional parameter for all methods and handle this inside each one, this seems like such a common use-case that it seems likely that flask-restful already has a solution built-in for this.

How do I handle per-method routes using flask-restful?

Upvotes: 1

Views: 1684

Answers (1)

ssears
ssears

Reputation: 101

The way I have tackled this in the past is create 2 resources:

api.add_resource(TestResrouces, '/testresource/')
api.add_resource(TestResource, '/testresource/<string: some_id>')

you will then need to create 2 classes. Then put your get/post/put code into functions etc...

class TestResrouces(restful.Resource):
    def get(self):
        response = some_function()
        jsonify(something1=response)

class TestResrouces(restful.Resrouce):
    def get(self, some_id):
        some_function(some_id)
        jsonify(something1=response            

Upvotes: 2

Related Questions