Can Flask have optional URL parameters? Can Flask have optional URL parameters? python python

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.


Almost the same as Audrius cooked up some months ago, but you might find it a bit more readable with the defaults in the function head - the way you are used to with python:

@app.route('/<user_id>')@app.route('/<user_id>/<username>')def show(user_id, username='Anonymous'):    return user_id + ':' + username


If you are using Flask-Restful like me, it is also possible this way:

api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint = 'user')

a then in your Resource class:

class UserAPI(Resource):  def get(self, userId, username=None):    pass


matomo