Flask only returning a single argument when parsing GET request

Viewed 1743

I'm trying to create filters on our REST API using Flask, but Flask only seems to return a single argument when the same key is duplicated in the query string.

For example:

from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify(request.args)

For request <localhost>/?test=a&test=b, the result is:

{
  "test": "a"
}

Since I want to reuse the filter argument to represent the AND logic for filtering, it would be convenient if Flask supported this. I realize that under the covers, Flask parses the request.args into a MultiDict object, which is probably why it cannot return multiple keys of the same name.

I assume I can access the raw query string somehow in Flask, but I haven't found that yet. I will update this post if I come across a solution, but if anyone else has ideas, please share.

3 Answers

Use request.args.getlist('test') to get all values for a given key.

According to rfc7159 and The JSON Data Interchange Format:

An object whose names are all unique is interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates.

The names within an object SHOULD be unique.

So, you can't make a json with the duplicated keys, You can handle this with some code like below:

@app.route('/')
def hello_world():
    return jsonify(dict(request.args))

result:

{
  "test": [
    "a", 
    "b"
  ]
}

you can do the following to get query strings

from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify(request.query_string)
Related