Reputation: 1957
I would like to know if there is any difference between:
@app.route('/api/users/<int:id>', methods=['GET'])
def get_user(id):
pass # handle user here with given id
and
@app.route('/api/users')
def get_user():
id = request.args.get('id')
# handle user here with given id
Furthermore, is there a way to get multiple parameters in the former? Can they be optional parameters?
Upvotes: 3
Views: 377
Reputation: 1520
The main difference is that the URL triggering your function will be different.
If you use the flask function url_for(that i REALLY recommend), the URL structure returned by the function will be different because all the variables that you use and are not part of the endpoint will be treated like query parameters.
So in this case you can change your route without impacting your existing codebase.
In other words in your case you would have:
Using method variables:
url_for('get_user', id=1) => '/api/users/1'
Without method variables:
url_for('get_user', id=1) => '/api/users?id=1'
Which approach is better depends from the context you are working on. If you want to realize a REST based API you should define the identifiers argument as path arguments and the metadata as query arguments(you can read more about that here).
Upvotes: 1
Reputation: 364
Yes, it is.
First method:
@app.route('/api/users/<int:id>', methods=['GET']
def get_user(id):
pass # handle user here with given id
Defines a route and a method. This function is only triggered with this method over this path.
Second method:
@app.route('/api/users')
def get_user():
id = request.args.get('id')
# handle user here with given id
It just defines a route. You can execute the function with all methods.
The route in the first method is: webexample.com/api/users/1
for user 1
The route in the second one is: webexample.com/api/users?id=1
for user 1
Upvotes: 3