0

I'm working on an API in Flask and one of the requirement is to keep multiple versions so end users will have the ability to switch between versions. I've started to maintain multiple version code bases based on recommendation(or answer) from this thread, but my question is, is there anyway to route user to hit different API versions just based on the parameter they pass in without actually changing url on their end.

For example:

http://testapp.com/api?v=1.0

will route to

http://testapp.com/1.0/api

and

http://testapp.com/api?v=2.0

will route to

http://testapp.com/2.0/api

I understand that using redirect(url_for('###')) with registered blueprint probably could solve this, but not ideal in my case(I'd like to keep the same url without redirecting but rendering the response from different version of api accordingly into current request)

Apologize in advance if my writing is not clear.

Community
  • 1
  • 1
xbb
  • 2,073
  • 1
  • 19
  • 34

2 Answers2

2

You may still use the view funcs, instead of redirect to another route, just call the view funcs.


For example:

from flask import request

from my_app.api.v1.views import index as v1_index
from my_app.api.v2.views import index as v2_index

.... other code ...


@app.route('/api')
def index():
    api_version = request.args.get('v', '1.0')
    if api_version == '1.0':
        return v1_index()
    elif api_version == '2.0':
        return v2_index()
    else:
        return 'Unsupported API version.'
lord63. j
  • 4,500
  • 2
  • 22
  • 30
1

You can do this in your flask application by checking request url before every request.

You can use flask before_request decorator to run a code before every request.

Below code will redirect urls as you wish

from flask import Flask, request, redirect, url_for
app = Flask(__name__)

@app.before_request
def check_url_and_redirect():
    if request.path[1:] == 'api':
        if request.args.get('v') == "1.0":
            return redirect(url_for('v1'))
        elif request.args.get('v') == "2.0":
            return redirect(url_for('v2'))

@app.route("/")
def hello():
    return "Hello World!"

@app.route("/1.0/api")
def v1():
    return "This is V1"

@app.route("/2.0/api")
def v2():
    return "This is V2"

if __name__ == "__main__":
    app.run(debug=True)
rezakamalifard
  • 1,289
  • 13
  • 24