Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
@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])
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 questionAsk a Question
731 491 924 answers to any question