Search code examples
pythonflaskflask-restplus

How to handle multiple 'GET' endpoints in a Flask-Restplus response class


I'm just starting learning Flask and are trying to create a simple API dealing with a data processing backend (named ATExplorer).

I started by creating a 'backend' namespace, i.e. backendAPI:

from flask import Flask, Blueprint, redirect, url_for
from flask_restplus import Resource, Api
from werkzeug.routing import Rule

app = Flask(__name__)
app.config.SWAGGER_UI_DOC_EXPANSION = 'list'
blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(blueprint, version=0.1, title='AT Pipeline API', doc='/swagger/')
app.register_blueprint(blueprint)
backendAPI = api.namespace('backend', description='Manage ATExplorer backend API.')

I want two endpoints, version, returning the version of the backend, e.g. 0.1 and status, returning the status of the backend, e.g. 'stopped', or 'running'

I created a response class and routes like this:

@backendAPI.route('/version', methods=['GET'])
@backendAPI.route('/status',  methods=['GET'])

class Backend(Resource):

     def get(self):
        #How to differentiate between the ../backend/version call and a 
        # ../backend/status call here??
        #if call is for status:
        #     return {'status': 'running'}
        #elif call is for version
        #     return {'version': '0.1'}

Guess this is a question of design. What 'design' is preferable for this case?

---- EDIT ----- The above code can be rewritten, achieving a desired end (client) result by the following:

class Backend(Resource):
    def __init__(self, api=None, *args, **kwargs):
         #The 'actual' backend resource
         self.backend = atp.backend

@backend_api.route('/status',  methods=['GET'])
class Dummy(Backend):
     def get(self):
         return {'status':self.backend.getStatus()}

@backend_api.route('/version',  methods=['GET'])
class Dummy(Backend):
     def get(self):
         return {'status':self.backend.getVersion()}

It seem flask allow multiple classes with the same name, doing different things based on the 'route' decorator, i.e. the class name is irrelevant.

Is there a 'text-book' way to express the above logic?


Solution

  • I believe it's more of a flask_restplus question, because in Flask you usually use methods as routes.

    Anyway, have you considered using two different classes for two different actions?

    @backendAPI.route('/version', methods=['GET'])
    class Version(Resource):
        def get(self):
             return flask.jsonify({"version_number": "0.1"})
    
    @backendAPI.route('/status', methods=['GET'])
    class Status(Resource):
        def get(self):
             return flask.jsonify({"status": "running"})