diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 7ae94fb0a8..e3caa1fdb8 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -222,12 +222,16 @@ So, when you need to declare a value as required while using `Query`, you can si ### Required, can be `None` { #required-can-be-none } -You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`. +You can declare that a parameter can include `None` in its type while still being required. To do that, you can declare that `None` is a valid type but simply do not declare a default value: {* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} +In this case, clients still have to provide the query parameter. +If the query parameter is omitted, FastAPI returns a validation error. +Also keep in mind that query parameters are strings in URLs, so clients don't directly send a JSON `null` value. + ## Query parameter list / multiple values { #query-parameter-list-multiple-values } When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in another way, to receive multiple values. diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py index 74c10b885d..40a2723da8 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py @@ -22,25 +22,34 @@ def get_client(request: pytest.FixtureRequest): return client -@pytest.mark.xfail( - reason="Code example is not valid. See https://github.com/fastapi/fastapi/issues/12419" -) def test_query_params_str_validations_no_query(client: TestClient): response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == { # pragma: no cover - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["query", "q"], + "msg": "Field required", + "input": None, + } + ] } -@pytest.mark.xfail( - reason="Code example is not valid. See https://github.com/fastapi/fastapi/issues/12419" -) def test_query_params_str_validations_empty_str(client: TestClient): response = client.get("/items/?q=") - assert response.status_code == 200 - assert response.json() == { # pragma: no cover - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "string_too_short", + "loc": ["query", "q"], + "msg": "String should have at least 3 characters", + "input": "", + "ctx": {"min_length": 3}, + } + ] }