From: dmontagu <35119617+dmontagu@users.noreply.github.com> Date: Mon, 26 Aug 2019 13:24:58 +0000 (-0700) Subject: :bug: Fix skip_defaults implementation when returning a Pydantic model (#422) X-Git-Tag: 0.36.0~2 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=38495fffa560fa57a8f0e6437d8e43c36c8e5612;p=thirdparty%2Ffastapi%2Ffastapi.git :bug: Fix skip_defaults implementation when returning a Pydantic model (#422) --- diff --git a/fastapi/routing.py b/fastapi/routing.py index 3c6774ceb3..930cbe001f 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -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 index 0000000000..8579b50ea5 --- /dev/null +++ b/tests/test_skip_defaults.py @@ -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": {}}