python route - Can Flask have optional URL parameters?

query restful (9)

@app.route('/', defaults={'path': ''})
@app.route('/< path:path >')
def catch_all(path):
    return 'You want path: %s' % path

Is it possible to directly declare a flask URL optional parameter?

Currently I'm proceeding the following way:

def show(userId, username=None):

Is there anything that can allow me to directly say that "username" is optional?

You can write as you show in example, but than you get build-error.

For fix this:

  1. print app.url_map () in you root .py
  2. you see something like:

<Rule '/<userId>/<username>' (HEAD, POST, OPTIONS, GET) -> user.show_0>


<Rule '/<userId>' (HEAD, POST, OPTIONS, GET) -> .show_1>

  1. than in template you can {{ url_for('.show_0', args) }} and {{ url_for('.show_1', args) }}

Another way is to write

@user.route('/<user_id>', defaults={'username': None})
def show(user_id, username):

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.

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):

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:

def show(user_id, username='Anonymous'):
    return user_id + ':' + username

I think you can use Blueprint and that's will make ur code look better and neatly.


from flask import Blueprint

bp = Blueprint(__name__, "example")

@bp.route("/example", methods=["POST"])
def example(self):

I know this post is really old but I worked on a package that does this called flask_optional_routes. The code is located at:

from flask import Flask

from flask_optional_routes import OptionalRoutes

app = Flask(__name__)
optional = OptionalRoutes(app)

def foobar(user_id, user_name=None):
    return 'it worked!'

if __name__ == "__main__":'', port=5000)

If you are happy with "blah" in somestring but want it to be a function call, you can probably do this

import operator

if not operator.contains(somestring, "blah"):

All operators in Python can be more or less found in the operator module including in.

python flask