1

I have two endpoints:

  • /api/v1/users
  • /api/v1/<resource>/users

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?

Dinko Pehar
  • 5,454
  • 4
  • 23
  • 57
Wander3r
  • 1,801
  • 17
  • 27

1 Answers1

2

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

Chris Charles
  • 4,406
  • 17
  • 31
  • Nice simple solution :) ! – Dinko Pehar Nov 12 '19 at 13:40
  • I had the same problem last week, but in my case the urls had not the same prefix, they were completely different. This happened because I had to implement a new version fo the api together with the old one. In the end I solved by copying and pasting the resource and registering the routes. – Pedro Silva Nov 19 '19 at 10:01