[BUG] Optional bool in query string always True when parameter not present
See original GitHub issueDescribe the bug
When query parameter of type Optional[bool]
is declared using Query
class parameter value is not correctly mapped and instead of None
it maps to instance of Schema
which when type casted to bool
returns True.
To Reproduce
Sample code:
class QueryParams(BaseModel):
foo: Optional[bool] = None
async def query_params(foo: Optional[bool] = Query(None, description="Some parameter")):
return QueryParams(foo=foo)
@api.get("/foo")
async def get(data: QueryParams = Depends(query_params)):
# When '/foo' is called (without any parameters) the 'foo' parameter
# inside 'data' has value of 'True' instead of 'None'.
return None
It however works fine if declared as just:
async def query_params(foo: Optional[bool] = None):
return QueryParams(foo=foo)
Expected behavior
Value should be assigned only if parameter is present in query string, None
otherwise.
Environment:
- OS: macOS
- FastAPI Version: 0.35
- Python version: 3.7.3
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Why does the Flask bool query parameter always evaluate to ...
In Flask, the query parameter values are always stored as strings. And unfortunately, calling bool() on a non-empty string will always be True...
Read more >What is wrong with boolean parameters?
A boolean argument indicates the function has 2 different behaviors. These 2 behaviors are probably tangled together. And this just calls for more....
Read more >Is it wrong to use a boolean parameter to determine behavior?
I think this question consists of two parts: 1. using a boolean variable to a method and 2. using a variable (boolean or...
Read more >Query Parameters - Routing - Ember Guides
Query parameters are optional key-value pairs that appear to the right of the ? in a URL. For example, the following URL has...
Read more >query-string - npm
Install. npm install query-string. Not npm install querystring !!!!! For browser usage, this package targets ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I got it. I refactored my code so I now have two function, both returning instance of my parameters models class.
Thanks for the help @dmontagu ! 🙇♂️ 🚀
Thanks for reporting back and closing the issue @LKay 🎉