Cannot control json serialization with custom response_class
See original GitHub issueclass 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.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:6
- Comments:8 (1 by maintainers)
Top Results From Across the Web
How to write custom converters for JSON serialization - .NET
This article shows how to create custom converters for the JSON serialization classes that are provided in the System.Text.Json namespace.
Read more >Failed to serialize the response in Web API with Json
I guess the xml serialiser can't serialise anonymous types and by removing it the result is serialised as json. If my guess is...
Read more >Exposing a custom type as a JSON string in an ASP.NET Core ...
For instance, you can define a custom converter to control how values of a given type are serialized or deserialized. Simple enough, right?...
Read more >Custom JSON Serialisation with System.Text.Json Converters
Text.Json. During serialisation, we can control this as I have done in the custom converter code above. We first get the actual type...
Read more >JSON Serialization and Deserialization - GraphQL .NET
Two libraries are available for assistance deserializing JSON-formatted GraphQL requests, and serializing GraphQL responses in a JSON format.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
+1
I’m currently using FastAPI for an API migration and want to use a custom json encoder for parity reasons. I discovered this after diffing responses from both APIs.
A small example of what I’m seeing (this timestamp is from a pandas dataframe):
Current FastAPI code
(shortened version of the current code in
get_request_handler
)serialize_response
calls the default FastAPI jsonable_encoder meaningresponse_data
has been encoded before theactual_response_class
is invoked.It seems like the recommendation in this thread is to explicitly return a custom
Response
inside each route – that does work, but it would be nice if we could just set adefault_response_class
when initializingFastAPI
and call it a day.Would it be possible to either:
raw_response
as a kwarg to actual_response_class?serialize_response
?Only a PR would really solve it, provided it’s considered as an issue, hence my “question” here. Two possible workarounds:
pydantic.json.ENCODERS_BY_TYPE[datetime] = lambda dt: dt.replace(tzinfo=pytz.utc).isoformat()