3

I want to handle a use case, where a key is passed to the GET request's query parameters, but without a value.

For example (request through Postman): Postman Request

In the case above, name is passed as a key but no value is set.

I tried using:

request.query_params

but, it doesn't seem to get the name, if the value is blank.

Chris
  • 18,724
  • 6
  • 46
  • 80

1 Answers1

3

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).

Chris
  • 18,724
  • 6
  • 46
  • 80
  • yeah, this seems the only way to properly deal with variable number of query parameters in the URL. – jdhao Jul 11 '23 at 12:26