Skip to content
Advertisement

Allow for multiple optional arguments in a Flask URL

So I have a flask URL, where there are 2 separate arguments. I want to run the same function with either no arguments, just the first or both. If no specific value is set, I want the unaccounted for arguments to get value None (as opposed to just not existing at all). My current solution involves using 3 @app.route statements, and I was wondering if there was something more efficient i’ve missed.

@app.route('/URL',defaults={'Arg1':None,'Arg2':None})
@app.route('/URL/<string:Arg1>',defaults={'Arg2':None})
@app.route('/URL/<string:Arg1>/<string:Arg2>')

Thanks!

Advertisement

Answer

In that case, just create simple route and access those variables in request.args like so:

@app.route('/test', methods=['GET'])
def test():
    arg1 = request.args.get('arg1', None)
    arg2 = request.args.get('arg2', None)
    if arg1:
        pass  # Do something with it
    elif arg2:
        pass  # Do something with it
    else:
        pass  # do something when no args given
    return jsonify()

And then in url you can pass like this:

/test
or
/test?arg2=321
or
/test?arg1=123
or
/test?arg1=123&arg2=321
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement