From 38495fffa560fa57a8f0e6437d8e43c36c8e5612 Mon Sep 17 00:00:00 2001 From: dmontagu <35119617+dmontagu@users.noreply.github.com> Date: Mon, 26 Aug 2019 06:24:58 -0700 Subject: [PATCH] :bug: Fix skip_defaults implementation when returning a Pydantic model (#422) --- fastapi/routing.py | 2 ++ tests/test_skip_defaults.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 tests/test_skip_defaults.py diff --git a/fastapi/routing.py b/fastapi/routing.py index 3c6774ceb..930cbe001 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 000000000..8579b50ea --- /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": {}}