Search code examples
pythonflaskurlpython-requestsflask-restful

If the query string of URL has multi-value parameters like ?name=a&name=b what happened to the second value in flask?


If the query string of URL has multi-value parameters like /obj?name=a&name=b what happened to the second value? Flask by default assumes query parameters to be of single-value.

the example for the parameters to be returned from JSON objects: obj=[{"name"="a","class"="x"},{"name"="b","class"="y"},{"name"="c","class"="z"}}

then the value returned by request.args.to_dict() is: {"name"="a","class"="x"}

what happened to the second value? required output is:

{"name"="a","class"="x"},{"name"="b","class"="y"}

@app.route('/obj', methods=['GET'])
def api_name():
    # Check if a name was provided as part of the URL.
    # If the name is provided, assign it to a variable.
    # If no name is provided, display an error in the browser.
    
    if 'name' in request.args:
        name = request.args['name'])
    else:
        return "Error: No name field provided. Please specify an name."

    # Create an empty list for our results
    results = []

    # Loop through the data and match results that fit the requested name.
    # name's are unique, but other fields might return many results
    for n in obj:
        if n['name'] == name:
            results.append(n)

    # Use the jsonify function from Flask to convert our list of
    # Python dictionaries to the JSON format.
    return jsonify(results)

Solution

  • # Get a specific parameter
    params=request.args.getlist('name')
    

    it converts the parameter into a list, in this case params=['a','b']