From 6ee86228a264ed00421494b7ee53b255badc1fa9 Mon Sep 17 00:00:00 2001 From: Mahdi Date: Wed, 29 Oct 2025 21:57:49 +0330 Subject: [PATCH] docs: clarify required query param that can be None --- .../tutorial/query-params-str-validations.md | 14 +++++++++++--- .../tutorial006c_fixed.py | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 docs_src/query_params_str_validations/tutorial006c_fixed.py diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index adf08a924..8988798d5 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -260,11 +260,19 @@ 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 make a query parameter **required** but still allow `None` as a value. -To do that, you can declare that `None` is a valid type but simply do not declare a default value: +This forces the client to **send the parameter**, even if the value is `null`. -{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} +Use `str | None` **without** a default value: + +{* ../../docs_src/query_params_str_validations/tutorial006c_fixed.py hl[9] *} + +/// tip | "How to send `None`" +To send `null`, use `?q=null` in the URL. + +FastAPI treats missing param as error (required), but `"null"` → `None` in Python. +/// ## Query parameter list / multiple values { #query-parameter-list-multiple-values } diff --git a/docs_src/query_params_str_validations/tutorial006c_fixed.py b/docs_src/query_params_str_validations/tutorial006c_fixed.py new file mode 100644 index 000000000..b8dcbd9aa --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial006c_fixed.py @@ -0,0 +1,16 @@ +from typing import Annotated + +from fastapi import FastAPI, Query + +app = FastAPI() + + +@app.get("/items/") +async def read_items(q: Annotated[str | None, Query(min_length=3)]): + # q is REQUIRED, but can be None if client sends ?q=null + if q == "null": + q = None + results = {"items": [{"item_id": "Foo"}]} + if q is not None: + results.update({"q": q}) + return results