Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃悰 Recurse into dataclass when encoding #4454

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion fastapi/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def jsonable_encoder(
sqlalchemy_safe=sqlalchemy_safe,
)
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)
return jsonable_encoder(dataclasses.asdict(obj))
if isinstance(obj, Enum):
return obj.value
if isinstance(obj, PurePath):
Expand Down
19 changes: 18 additions & 1 deletion tests/test_serialize_response_dataclass.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from dataclasses import dataclass
from datetime import date
from typing import List, Optional

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic.dataclasses import dataclass

app = FastAPI()

Expand All @@ -14,6 +15,11 @@ class Item:
owner_ids: Optional[List[int]] = None


@dataclass
class EncodingItem:
date: date


@app.get("/items/valid", response_model=Item)
def get_valid():
return {"name": "valid", "price": 1.0}
Expand All @@ -29,6 +35,11 @@ def get_coerce():
return {"name": "coerce", "price": "1.0"}


@app.get("/items/encoding", response_model=EncodingItem)
def get_encoding():
return {"date": date(2022, 1, 20)}


@app.get("/items/validlist", response_model=List[Item])
def get_validlist():
return [
Expand Down Expand Up @@ -82,6 +93,12 @@ def test_coerce():
assert response.json() == {"name": "coerce", "price": 1.0, "owner_ids": None}


def test_encoding():
response = client.get("/items/encoding")
response.raise_for_status()
assert response.json() == {"date": "2022-01-20"}


def test_validlist():
response = client.get("/items/validlist")
response.raise_for_status()
Expand Down