]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
✨ Allow `None` as return type for bodiless responses (#9425)
authorRobert Hofer <1058012+hofrob@users.noreply.github.com>
Sat, 20 Sep 2025 18:44:43 +0000 (20:44 +0200)
committerGitHub <noreply@github.com>
Sat, 20 Sep 2025 18:44:43 +0000 (18:44 +0000)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
fastapi/dependencies/utils.py
tests/test_return_none_stringified_annotations.py [new file with mode: 0644]

index 8dd0a14c8a1d4ac7a5808759b2fcb57a10b3e4f3..dc663f5489fc701ed0b0d6e555d0cdcfc16b121f 100644 (file)
@@ -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 (file)
index 0000000..be052d5
--- /dev/null
@@ -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