Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a resource with multiple endpoints with Flask-Restful?

Here's a simple Flask-Restful resource:

class ListStuff(Resource):
    def get(self):
       stuff = SomeFunctionToFetchStuff()
       if re.match('/api/', request.path):
           return {'stuff': stuff}
       return make_response("{}".format(stuff), 200, {'Content-Type': 'text/html'})

api.add_resource(ListStuff, '/list', '/api/list', endpoint='list')

My idea is to allow users to call both /list and /api/list. If they use the first URL, they will get back an HTML representation of the data. If they use the second URL, they will get a JSON representation.

My trouble is when I want to access the URL of this endpoint elsewhere in the program. I can't just use url_for('list'), because that will always return /list , no matter whether the user accessed http://host.example.com/list or http://host.example.com/api/list

So how can I build the URL for /api/list ?

like image 448
David White Avatar asked Sep 08 '25 11:09

David White


1 Answers

Looks like Hassan was on the right track - I can add a new resource for the same class but give it a different endpoint.

api.add_resource(ListStuff, '/list', endpoint='list')
api.add_resource(ListStuff, '/api/list', endpoint='api-list')

>>> print('URL for "list" is "{}"'.format(url_for('list'))
>>> print('URL for "api-list" is "{}"'.format(url_for('api-list'))

URL for "list" is "/list"
URL for "api-list" is "/api/list"
like image 101
David White Avatar answered Sep 11 '25 04:09

David White