Search code examples
pythonflaskflask-restful

Flask-RESTful alias


I would like to create an alias between two resources.

from flask import Flask
from flask_restful import Api, Resource

class api_v1_help(Resource):
    def get(self):
        html_file = "API V1"
        return (html_file, 200, {'Content-Type': 'text/html; charset=utf-8'})

class api_v2_help(Resource):
    def get(self):
        html_file = "API V2"
        return (html_file, 200, {'Content-Type': 'text/html; charset=utf-8'})


app = Flask(__name__)
api = Api(app)

# API (current)
api.add_resource(api_v1_help, '/api/help')

# API v1
api.add_resource(api_v1_help, '/api/v1/help')

# API v2
api.add_resource(api_v2_help, '/api/v2/help')

if __name__ == '__main__':
    # Start app
    app.run(debug=True,port=5000)

This is giving the following error : AssertionError: View function mapping is overwriting an existing endpoint function: api_v1_help

I can change the code like this :

api.add_resource(api_v1_help, '/api/help', '/api/v1/help') 

but I would like to know if there is another solution with flask-restful to handle an alias by linking two API endpoints to the same function?

I search to group the calls for a specific API version.


Solution

  • Use Flask.add_url_route instead:

    # API v1
    api.add_resource(api_v1_help, '/api/v1/help')
    
    # API v2
    api.add_resource(api_v2_help, '/api/v2/help')
    
    # API (current)
    app.add_url_rule('/api/help', endpoint='api_v1_help')
    

    By default, endpoint is set as the name of the view class, so you can use 'api_v1_help' as the name after the add_resource call.