diff --git a/fastapi/encoders.py b/fastapi/encoders.py index bececedae..25cd0b026 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -32,7 +32,9 @@ def jsonable_encoder( if exclude is not None and not isinstance(exclude, set): exclude = set(exclude) if isinstance(obj, BaseModel): - encoder = getattr(obj.Config, "json_encoders", custom_encoder) + encoder = getattr(obj.Config, "json_encoders", {}) + if custom_encoder: + encoder.update(custom_encoder) if PYDANTIC_1: obj_dict = obj.dict( include=include, diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index 0975430d7..97fbf6e6d 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -105,3 +105,18 @@ def test_encode_model_with_alias_raises(): def test_encode_model_with_alias(): model = ModelWithAlias(Foo="Bar") assert jsonable_encoder(model) == {"Foo": "Bar"} + + +def test_custom_encoders(): + class safe_datetime(datetime): + pass + + class MyModel(BaseModel): + dt_field: safe_datetime + + instance = MyModel(dt_field=safe_datetime.now()) + + encoded_instance = jsonable_encoder( + instance, custom_encoder={safe_datetime: lambda o: o.isoformat()} + ) + assert encoded_instance["dt_field"] == instance.dt_field.isoformat()