Skip to content

Accept single bare values for list-typed query parameters - #124

Open
semohr wants to merge 1 commit into
pgjones:mainfrom
semohr:simplify_validate_querystring_syntax
Open

semohr wants to merge 1 commit into
pgjones:mainfrom
semohr:simplify_validate_querystring_syntax

Conversation

@semohr

@semohr semohr commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

validate_querystring only produces a list when a key occurs more than once. For a field declared as list[int], a client sending a one-item array gets a 400 instead of [1].

This PR enhances validate_querystring to treat a single occurrence of a parameter declared as a list as a one-element list, based on the model's annotations. It works for all model kinds and keeps the existing [] suffix and repeated forms working.

The following requests are now treated equally:

/?elems=2             -> 200 {"elems": [2]} # This was not possible without workaround before
/?elems[]=2           -> 200 {"elems": [2]}
/?elems=2&elems=3     -> 200 {"elems": [2, 3]}
/?elems[]=2&elems[]=3 -> 200 {"elems": [2, 3]}

Details Before, accepting a single value for a list field required special pydantic syntax (a ``BeforeValidator`` per field), which is now unnecessary (also wasnt really possible with msgspec):
from typing import Annotated

from pydantic import BaseModel
from pydantic.functional_validators import BeforeValidator
from quart_schema import validate_querystring

def _to_list(value: str | list[str]) -> list[str]:
    if isinstance(value, list):
        return value
    else:
        return [value]

class Query(BaseModel):
    keys: Annotated[Optional[List[str]], BeforeValidator(_to_list)] = None

@app.route("/")
@validate_querystring(Query)
async def index(query_args: Query):
    ...

@semohr
semohr force-pushed the simplify_validate_querystring_syntax branch from 999b328 to 2e78741 Compare September 8, 2026 22:11
@semohr

semohr commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

@pgjones Short ping for visibility.

Was thinking this is a good addition as it simplifies this quite common usecase imo.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant