Skip to content

Cannot control json serialization with custom response_class #2117

@tangi75

Description

@tangi75
class CustomJSONResponse(JSONResponse):
    media_type = "application/json"

    def render(self, content: typing.Any) -> bytes:
        return dumps(content)

With dumps being a custom function, managing datetime values specifically.

@router.post("/requests")
async def insert_user_request(request: Request):
   return CustomJSONResponse(content={"timestamp": datetime.now()}, status_code=HTTP_201_CREATED)

Will work as expected but

@router.post("/requests", response_class=CustomJSONResponse, status_code=HTTP_201_CREATED)
async def insert_user_request(request: Request):
    return {"timestamp": datetime.now()}

Will fail to use the custom dump function.

The cause is in https://github.com/tiangolo/fastapi/blob/master/fastapi/routing.py#L190 : serialize_response (which calls jsonable_encoder) is called before the response_class instantiation (https://github.com/tiangolo/fastapi/blob/master/fastapi/routing.py#L201) so datetime values are converted to str prematurely.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions