From b51ec36f2e442495de5e4c22ae51a8f5c44917eb Mon Sep 17 00:00:00 2001 From: Robert Hofer <1058012+hofrob@users.noreply.github.com> Date: Sat, 20 Sep 2025 20:44:43 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=20Allow=20`None`=20as=20return=20t?= =?UTF-8?q?ype=20for=20bodiless=20responses=20(#9425)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/dependencies/utils.py | 2 ++ .../test_return_none_stringified_annotations.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 tests/test_return_none_stringified_annotations.py diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 8dd0a14c8..dc663f548 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -254,6 +254,8 @@ def get_typed_annotation(annotation: Any, globalns: Dict[str, Any]) -> Any: if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) + if annotation is type(None): + return None return annotation diff --git a/tests/test_return_none_stringified_annotations.py b/tests/test_return_none_stringified_annotations.py new file mode 100644 index 000000000..be052d532 --- /dev/null +++ b/tests/test_return_none_stringified_annotations.py @@ -0,0 +1,17 @@ +import http + +from fastapi import FastAPI +from fastapi.testclient import TestClient + + +def test_no_content(): + app = FastAPI() + + @app.get("/no-content", status_code=http.HTTPStatus.NO_CONTENT) + def return_no_content() -> "None": + return + + client = TestClient(app) + response = client.get("/no-content") + assert response.status_code == http.HTTPStatus.NO_CONTENT, response.text + assert not response.content