Wander3r
Wander3r

Reputation: 1881

Two urls with difference of one optional parameter to map to same resource in flask restful

I have two endpoints:

I have a class that handles for the latter like this

class ListUsers(Resource):
    def post(self,resource):
         // get the list of users under that resource

api.addResource(ListUsers,'/api/v1/<resource>/users')

If the resource is not specified, I want to list users from all resources. Is it possible to map both the urls to the same class ListUsers instead of writing another class for the first url?

Upvotes: 2

Views: 650

Answers (1)

Chris Charles
Chris Charles

Reputation: 4446

According the the docs and source code for flask-restful, you can pass multiple urls to match to addResource.

like:

class ListUsers(Resource):
    def post(self, resource=None):
        // get the list of users under that resource

api.addResource(ListUsers, '/api/v1/<resource>/users', '/api/v1/users')

Another example: https://stackoverflow.com/a/56250131/1788218

Useful docs: https://buildmedia.readthedocs.org/media/pdf/flask-restful/latest/flask-restful.pdf

Upvotes: 3

Related Questions