Z
Z
zasqer2014-08-03 23:57:07
Flask
zasqer, 2014-08-03 23:57:07

How to make a parameter in url routing optional?

I am creating a REST API, endpoint user and want to make the id parameter optional.
The end result should be:
1)GET '/user' returns all users
2)GET '/user/1' returns the user with id == 1

temporarily solved the problem by setting two different functions - users() and user(id)

@app.route('/user', methods=['GET', 'POST'])
def users():
    if request.method == 'GET':
        users = User.query.all()
        return jsonify(num_results=len(users),
                       objects=[user.serialize() for user in users])

@app.route('/user/<int:id>', methods=['GET', 'PUT', 'DELETE'])
def user(id):
    if request.method == 'GET':
        user = User.query.filter(User.id == id).first()
        return jsonify(user=user.name)


is there a better way to make a parameter optional?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2014-08-04
@zasqer

@app.route('/user', methods=['GET', 'POST'])
@app.route('/user/<int:id>', methods=['GET', 'PUT', 'DELETE'])
def users(id=None):
    if request.method == 'GET':
        users = User.query.all()
        return jsonify(num_results=len(users),
                       objects=[user.serialize() for user in users])

A
akaRem, 2014-11-03
@akaRem

There is another option

from flask import Flask
app = Flask(__name__)

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

if __name__ == '__main__':
    app.run()

% curl 127.0.0.1:5000          # Matches the first rule
You want path:  
% curl 127.0.0.1:5000/foo/bar  # Matches the second rule
You want path: foo/bar

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question