Search code examples
pythonpython-3.xflaskflask-restful

Difference between GET data as a function parameter and an item from requests.arg


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?


Solution

  • 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