Both request.query_params
and request.url.query
(which is used to get the raw query string) should return keys with blank values as well.
In a scenario where you expect a list
of values for a specific key, and may appear multiple times in the URL, using dict(request.query_params)
to get a dictionary of key-value pairs wouldn't work as expected. For instance, ?foo=2&foo=10&bar=7
would return {"foo":"10","bar":"7"}
instead of {"foo":["2","10"],"bar":"7"}
. In that case, you may consider following an approach similar to this answer, using urllib.parse.parse_qs
. To include keys having blank values, you can set the keep_blank_values
flag to True
, as described in the documentation:
The optional argument keep_blank_values
is a flag indicating whether
blank values in percent-encoded queries should be treated as blank
strings. A true
value indicates that blanks should be retained as
blank strings. The default false
value indicates that blank values
are to be ignored and treated as if they were not included.
Example:
from fastapi import FastAPI, Request
from urllib.parse import parse_qs
app = FastAPI()
@app.get("/")
def main(request: Request):
q_params = parse_qs(request.url.query, keep_blank_values=True)
d = dict((k, v if len(v)>1 else v[0])
for k, v in q_params.items())
return d
On a side note, if the query parameters are known beforehand and aren't arbitrary, you can always declare them as Optional parameters in your endpoint (see Query Parameters documentation).