mirror of
https://github.com/fastapi/fastapi.git
synced 2026-11-02 22:24:34 -05:00
📝 Clarify boolean query parameter parsing (#16569)
This commit is contained in:
1 parent
5c3e3d47ab
commit
f23cd4f095
2 files changed
+33
-1
No files matched your search
@@ -107,7 +107,13 @@ or
|
||||
http://127.0.0.1:8000/items/foo?short=yes
|
||||
```
|
||||
|
||||
or any other case variation (uppercase, first letter in uppercase, etc), your function will see the parameter `short` with a `bool` value of `True`. Otherwise as `False`.
|
||||
or any other case variation (uppercase, first letter in uppercase, etc), your function will see the parameter `short` with a `bool` value of `True`.
|
||||
|
||||
Values such as `0`, `false`, `off`, and `no` (including case variations) are converted to `False`.
|
||||
|
||||
If `short` is omitted, **FastAPI** uses its default value, which is `False` in this example.
|
||||
|
||||
An empty value (`?short=`) or an unrecognized value (for example, `?short=maybe`) produces a `422` validation error.
|
||||
|
||||
|
||||
## Multiple path and query parameters { #multiple-path-and-query-parameters }
|
||||
|
||||
@@ -50,6 +50,32 @@ def test_read_user_item(client: TestClient, path, expected_json):
|
||||
assert response.json() == expected_json
|
||||
|
||||
|
||||
@pytest.mark.parametrize("short", ["0", "false", "off", "no", "FaLsE"])
|
||||
def test_boolean_query_false(client: TestClient, short: str):
|
||||
response = client.get("/items/foo", params={"short": short})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"item_id": "foo",
|
||||
"description": "This is an amazing item that has a long description",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("short", ["", "maybe"])
|
||||
def test_invalid_boolean_query(client: TestClient, short: str):
|
||||
response = client.get("/items/foo", params={"short": short})
|
||||
assert response.status_code == 422
|
||||
assert response.json() == {
|
||||
"detail": [
|
||||
{
|
||||
"type": "bool_parsing",
|
||||
"loc": ["query", "short"],
|
||||
"msg": "Input should be a valid boolean, unable to interpret input",
|
||||
"input": short,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_openapi_schema(client: TestClient):
|
||||
response = client.get("/openapi.json")
|
||||
assert response.status_code == 200
|
||||
|
||||
Reference in new issue
Block a user