Can Flask have optional URL parameters?
Another way is to write
@user.route('/<user_id>', defaults={'username': None})
@user.route('/<user_id>/<username>')
def show(user_id, username):
pass
But I guess that you want to write a single route and mark username
as optional? If that's the case, I don't think it's possible.
Flask - Optional path args
Optional parameters are allowed in Flask.
You can define multiple rules for same function. Here is the documentation on URL Route Registrations.
Updated code:
import flask
win = flask.Flask(__name__)
@win.route('/<name>/', defaults={'ints': None, 'floats': None})
@win.route('/<name>/<int:ints>/', defaults={'floats': None})
@win.route("/<name>/<int:ints>/<float:floats>/")
def web(name, ints, floats):
if ints!=None and floats!=None:
return "Welcome Back: %s, Your Int: %d, Your Float: %f" % (name, ints, floats)
elif ints!=None and floats==None:
return "Welcome Back: %s, Your Int: %d" % (name, ints)
return "Welcome Back: %s" % (name)
win.run(debug=True)
When chrome or any other web browser requests either of these URLs, Flask will invoke the associated function along with the arguments provided in the url. If no or less arguments are provided then default values of arguments will be used.
Screenshots:
Three parameters:
Two parameters:
One parameter:
Flask - Routing with multiple optional parameters
You can use filter in the URL instead of "sub-resources".
Then you can put search arguments in any order in your request:/search?pg=<pg>&types=<types>
Inside the flask view function you can retrieve parameters from the request object:
@app.route('/search/')
def search():
pg = request.args.get('pg')
...
Multiple optional parameters in flask-restful API?
Solved by using flask-resful's reqparse.
More info here: https://blog.miguelgrinberg.com/post/designing-a-restful-api-using-flask-restful
from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
app = Flask(__name__)
api = Api(app)
class print_stuff(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('name', type = str, default='')
self.reqparse.add_argument('email', type = str, default='')
self.reqparse.add_argument('address', type = str, default='')
self.reqparse.add_argument('age', type = str, default='')
super(hlr_lookup, self).__init__()
def get(self):
args = self.reqparse.parse_args()
return {
'your name is':args['name'],
'your email is': args['email'],
'your address is': args['address'],
'your age is': args['age']
}
api.add_resource(print_stuff,'/overflow_test')
if __name__ == '__main__':
app.run(debug=True)
Now I can call the api like this:
127.0.0.1:5000/print_stuff?name=John&age=23&address=main street new york&email=something@gmail.com
Allow for multiple optional arguments in a Flask URL
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
Related Topics
Python Extending with - Using Super() Python 3 VS Python 2
Number of Days Between 2 Dates, Excluding Weekends
Find Longest Repetitive Sequence in a String
List of Dicts To/From Dict of Lists
Django Aggregation: Summation of Multiplication of Two Fields
Removing Unicode \U2026 Like Characters in a String in Python2.7
Should I Call Close() After Urllib.Urlopen()
How to Set Folder Permissions in Windows
What Does the Term "Broadcasting" Mean in Pandas Documentation
Asyncio.Sleep() VS Time.Sleep()
Python String 'Join' Is Faster () Than '+', But What's Wrong Here
How to Remove the Left Part of a String
Check If a File Is Open in Python