]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
:bug: Fix skip_defaults implementation when returning a Pydantic model (#422)
authordmontagu <35119617+dmontagu@users.noreply.github.com>
Mon, 26 Aug 2019 13:24:58 +0000 (06:24 -0700)
committerSebastián Ramírez <tiangolo@gmail.com>
Mon, 26 Aug 2019 13:24:58 +0000 (08:24 -0500)
fastapi/routing.py
tests/test_skip_defaults.py [new file with mode: 0644]

index 3c6774ceb3d354126669075646b7813b0fe7be55..930cbe001ff1d4e6db92fbc187455ad80a12b57e 100644 (file)
@@ -52,6 +52,8 @@ def serialize_response(
             errors.extend(errors_)
         if errors:
             raise ValidationError(errors)
+        if skip_defaults and isinstance(response, BaseModel):
+            value = response.dict(skip_defaults=skip_defaults)
         return jsonable_encoder(
             value,
             include=include,
diff --git a/tests/test_skip_defaults.py b/tests/test_skip_defaults.py
new file mode 100644 (file)
index 0000000..8579b50
--- /dev/null
@@ -0,0 +1,29 @@
+from typing import Optional
+
+from fastapi import FastAPI
+from pydantic import BaseModel
+from starlette.testclient import TestClient
+
+app = FastAPI()
+
+
+class SubModel(BaseModel):
+    a: Optional[str] = "foo"
+
+
+class Model(BaseModel):
+    x: Optional[int]
+    sub: SubModel
+
+
+@app.get("/", response_model=Model, response_model_skip_defaults=True)
+def get() -> Model:
+    return Model(sub={})
+
+
+client = TestClient(app)
+
+
+def test_return_defaults():
+    response = client.get("/")
+    assert response.json() == {"sub": {}}