diff --git a/fastapi/encoders.py b/fastapi/encoders.py index c9f882d2ba..4cc86abe7c 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -82,7 +82,7 @@ def decimal_encoder(dec_value: Decimal) -> int | float: ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = { - bytes: lambda o: o.decode(), + bytes: lambda o: o.decode(errors="replace"), Color: str, PyExtraColor: str, datetime.date: isoformat, diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index c23a9e5d79..2ccd475198 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -299,6 +299,11 @@ def test_decimal_encoder_infinity(): assert isinf(jsonable_encoder(data)["value"]) +def test_encode_bytes_with_invalid_utf8_does_not_raise(): + data = {"value": b"\xff"} + assert jsonable_encoder(data) == {"value": "\ufffd"} + + def test_encode_deque_encodes_child_models(): class Model(BaseModel): test: str