Replies: 5 comments
-
@LKay from typing import Optional
from pydantic import BaseModel
from starlette.testclient import TestClient
from fastapi import FastAPI, Depends, Query
app = FastAPI()
class QueryParams(BaseModel):
foo: Optional[bool] = None
async def query_params(foo: Optional[bool] = Query(None, description="Some parameter")):
return QueryParams(foo=foo)
@app.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 data.foo
def test_optional_bool():
assert TestClient(app).get("/foo").content == b"null" Did I miss something? |
Beta Was this translation helpful? Give feedback.
-
Oh, sorry I missed one more part. It happens when there is another wrapping function for parameters ie. for admin and non-admin parameters, such as: class QueryParams(BaseModel):
foo: Optional[bool] = None
bar: Optional[bool] = None # ie. only admin param
async def query_params_admin(foo: Optional[bool] = Query(None, description="Some parameter"), bar: Optional[bool] = Query(None, description="Some parameter")):
return QueryParams(foo=foo, bar=bar)
async def query_params(foo: Optional[bool] = Query(None, description="Some parameter")):
return await query_params_admin(foo) |
Beta Was this translation helpful? Give feedback.
-
The problem in your example is that you are calling If you make a self-contained example like the one I posted above that isn't working the way you'd expect, I can show you options for how to refactor it into something that works. |
Beta Was this translation helpful? Give feedback.
-
I got it. I refactored my code so I now have two function, both returning instance of my parameters models class. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help @dmontagu ! 🙇♂️ 🚀 Thanks for reporting back and closing the issue @LKay 🎉 |
Beta Was this translation helpful? Give feedback.
-
Describe the bug
When query parameter of type
Optional[bool]
is declared usingQuery
class parameter value is not correctly mapped and instead ofNone
it maps to instance ofSchema
which when type casted tobool
returns True.To Reproduce
Sample code:
It however works fine if declared as just:
Expected behavior
Value should be assigned only if parameter is present in query string,
None
otherwise.Environment:
Beta Was this translation helpful? Give feedback.
All reactions