You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
msgpack response if client asks for application/x-msgpackΒ #521
hi,
we are in the process of evaling fastapi for a large app migration from flask. Quick question on a very interesting and useful piece of functionality.
This builds upon the validations you have created for encoding json data and will be very useful for us out-of-the-box.
https://msgpack.org/index.html is an enhancement to json which is highly compressed. There are some benchmarks that show it is as fast as protocol buffers...while making it a drop-in alternative to json.
To be fair, it may be same size as gzipped json responses...but after having done android app deployments over a million devices in the field in asia, we realized that one has to write custom compression/decompression for gzipped json response handling. However msgpack has fairly well supported libraries.
This enhancement request is for fastapi to respond in msgpack if the requesting client ask for the mimetype application/x-msgpack. The default behavior continues to be the same as currently.
There is no impact to any client of a fastapi deployment unless they specifically ask for msgpack (in which case, they will get better performance).
I'm also pasting some criticisms of msgpack and comparisons with competing/derived json formats like CBOR
@sandys
I think fastapi may actually be relatively well suited to handle this now without modifications.
If your top priority is just reducing bandwidth usage, I think it should be straightforward to implement converting the json responses to msgpack (in the presence of the appropriate mimetype request) as an ASGI middleware. I imagine that would involve parsing the json and dumping it to msgpack format, so would come with some processing overhead. But that overhead would probably be negligible compared to network, especially if bandwidth is the source of the concern.
If you really want to avoid the reparsing, I think this would also be possible by creating a custom starlette response that holds the python dict you want to serialize (rather than encoded json), and adding a middleware that converts responses of that type to a new starlette.Response with msgpack-encoded contents.
If you are serious about this and want/need a little more guidance than provided above, I can put together more of a skeleton implementation.
I'd suggest taking a look at starlette.responses.JSONResponse -- it looks like you could pretty easily create a MsgpackResponse by defining an appropriate render function (e.g., using msgpack-python). Then, you could have your endpoints return msgpack-encoded data by setting response_class=MsgpackResponse. That wouldn't allow for dynamic determination of the response type based on the request, but maybe there is still a way to achieve that...
(Certainly, in the worst case, you could just perform a reparsing of the JSONResponse in a middleware.)
@sandys
Actually, I got interested in this and was able to throw together a working example -- not quite how I expected it would need to go, and it has some hacks that could probably be removed (maybe would require a feature request or two), but it works:
First I want to thank you for taking the trouble to do this !!
I really appreciate this and have newfound respect for the great community
around fastapi.
I'm still requesting for this to be made a first class feature within
fastapi for the benefit it provides to the larger community
On Fri, 13 Sep, 2019, 04:05 dmontagu, ***@***.***> wrote:
@sandys <https://github.com/sandys>
Actually, I got interested in this and was able to throw together a
working example -- not quite how I expected it would need to go, and it has
some minor hacks, but it works:
from typing import Any, Dict, List, Type
import msgpackfrom fastapi import FastAPIfrom fastapi.routing import APIRoute, get_appfrom starlette.background import BackgroundTaskfrom starlette.requests import Requestfrom starlette.responses import JSONResponse, Responsefrom starlette.routing import request_responsefrom starlette.testclient import TestClient
class MsgpackResponse(Response):
media_type = "application/msgpack"
def render(self, content: Any) -> bytes:
return msgpack.packb(content)
class MultiResponse(JSONResponse):
serialization_header = "X-Serialization"
default_response_class = JSONResponse
response_class_map: Dict[str, Type[Response]] = {"msgpack": MsgpackResponse}
def __init__(
self,
content: Any = None,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
) -> None:
self.content = content
super().__init__(content, status_code, headers, media_type, background)
def for_request(self, request: Request) -> Response:
serialization_method = request.headers.get(self.serialization_header)
response_class = self.response_class_map.get(
serialization_method, self.default_response_class
)
return response_class(
content=self.content,
status_code=self.status_code,
headers=self.headers,
media_type=self.media_type,
background=self.background,
)
class MultiAPIRoute(APIRoute):
def __init__(self, *args: Any, **kwargs: Any) -> None:
if kwargs["response_class"] is JSONResponse:
kwargs["response_class"] = MultiResponse
super().__init__(*args, **kwargs)
# Copied below from the end of the APIRoute init; overwriting the self.app with a modified version
base_app_func = get_app(
dependant=self.dependant,
body_field=self.body_field,
status_code=self.status_code,
response_class=self.response_class,
response_field=self.secure_cloned_response_field,
response_model_include=self.response_model_include,
response_model_exclude=self.response_model_exclude,
response_model_by_alias=self.response_model_by_alias,
response_model_skip_defaults=self.response_model_skip_defaults,
dependency_overrides_provider=self.dependency_overrides_provider,
)
async def app_func(request: Request) -> Response:
response = await base_app_func(request)
if isinstance(response, MultiResponse):
response = response.for_request(request)
return response
self.app = request_response(app_func)
app = FastAPI()
app.router.route_class = MultiAPIRoute
@app.get("/", response_model=List[int])async def root():
return [1, 2, 3]
client = TestClient(app)print(client.get("/").content)# b'[1,2,3]'
print(client.get("/", headers={"X-Serialization": "msgpack"}).content)# b'\x93\x01\x02\x03'
β
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#521>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AAASYUZBI3NJGYZU6MJ4UGLQJK73JANCNFSM4IVUIA7A>
.
I've reworked it to be substantially simpler, and also I've put some thought into what first-class support could/should look like in FastAPI.
Here's a msgpack-specific simplified implementation (with minimal docs) that runs as is to show how simple it is:
(note include_both_serialization_routes could be removed with a relatively minor feature request, described below).
Getting this "built in" would probably require the following two feature requests:
starlette: Add this class as a Response (NOT as a subclass of JSONResponse)
fastapi: Allow non-None response_model if using a non-subclass of JSONResponse
(I think it is unlikely that fastapi would add this directly, but I suppose it's possible.)
Given how short it is, I expect it may be better not to upstream it, and have to deal with the additional testing burden, etc.
classOverrideResponseClassRoute(APIRoute):
detection_header: ClassVar[str]
detection_header_match: ClassVar[str]
response_class_mapping: ClassVar[JSONResponse]
include_in_schema_override: ClassVar[Optional[bool]] =Nonedef__init_subclass__(cls) ->None:
missing_attributes: List[str] = []
forattributeinget_type_hints(OverrideResponseClassRoute):
ifnothasattr(cls, attribute):
missing_attributes.append(attribute)
ifmissing_attributes:
raiseTypeError(f"{cls.__name__} did not define the following attributes: {missing_attributes}")
def__init__(self, *args: Any, **kwargs: Any) ->None:
""" This could be made more typesafe by repeating all the args/kwargs explicitly. """include_in_schema=kwargs["include_in_schema"] ifself.include_in_schema_overrideisNoneelseNoneresponse_class=self.response_class_mapping.get(kwargs["response_class"], kwargs["response_class"])
kwargs["include_in_schema"] =include_in_schemakwargs["response_class"] =response_classsuper().__init__(*args, **kwargs)
defmatches(self, scope: Scope) ->Tuple[Match, Scope]:
ifnotRequest(scope).headers.get(self.detection_header) ==self.detection_header_match:
returnMatch.NONE, {}
returnsuper().matches(scope)
classMsgpackRoute(OverrideResponseClassRoute):
detection_header="Accept"detection_header_match="application/x-msgpack"response_class_mapping= {JSONResponse: MsgpackResponse}
include_in_schema_override=False
@sandys is this what you had in mind for having the client specify the mimetype? One might want to parse the accept header into a list of strings, but this works for now.
This function could be removed if fastapi supported route_class parameter in APIRouter.include_router. I personally think this is a reasonable feature request that should be added.
With the above feature requests, even without built-in support for msgpack, the ultimate usage would be as simple as:
@sandys Would this be good enough for you to consider it as being supported in a "first class" way? If not, is there anything specific you don't like, or think is missing?
Edit: I suppose it would be good to add support for receiving msgpack payloads as well; this would probably need to be done in a middleware.
Rereading your original comment, I think I see more explicitly what you are looking for:
This enhancement request is for fastapi to respond in msgpack if the requesting client ask for the mimetype application/x-msgpack.
I didn't think about the idea that this would just be handled by default for all apps. I think this could be done inside FastAPI using an approach similar to that proposed above, and could be an option to enable if msgpack is present. But I don't know if it's worth the additional maintenance burden on fastapi; I don't know how commonly used this serialization format is (especially compared to JSON).
@tiangolo If I had to guess, I would assume that this feature request is outside the scope of what you'd want to support out of the box. But if that's wrong, let me know and I can take a stab at a PR incorporating this directly into FastAPI.
@dmontagu i would like to again add a million thanks to the work you have done above. I do not think i would have been able to figure this stuff out without putting weeks into it...and maybe still not (or would have given up).
And that is a good context to why this is important. I come from the Rails world and I frequently read about how big sites use Rails (e.g. here) . The key to observe here is "batteries included" but not linked to the batteries.
For example in Rails you can skip all the "batteries included" functionality by opt-out. Rails is opt-in by default ...and that is what im asking Fastapi devs to consider.
rails new app_name --skip-action-cable --skip-action-text
Fastapi is quickly becoming more than just a wrapper on top of starlette. And that is a tradeoff between functionality versus simplicity (and even performance). For example Starlette still beats Fastapi on performance, but for a developer, there is no question which he will choose. It may come as no surprise that most people start with https://github.com/tiangolo/full-stack-fastapi-postgresql . I personally would not have been able to begin with Fastapi if i didnt have that starter readymade.
I think (and I really hope) that Fastapi keeps adding batteries , which are skippable. Because i know for sure - that without you writing the code above, there was an almost zero chance that I would have achieved it myself in time.
however, i do so the reluctance devs may have to tie it to msgpack at this point. Fair enough - however i would really request for you to put in the code that enables MsgpackResponse and MsgpackRoute. That would be a superb help to add new mimetypes and response serialization formats
@dmontagu your code doesnt work both ways right ? it doesnt accept msgpack data in the request. In Asia, the big bottlenecks is when data is sent from mobile devices (which is 90% of all internet devices) to the server.
@sandys yes, it doesnβt handle that yet. That could probably be done via middleware, though I donβt know how easy starlette makes it. Iβll see if I can figure it out.
With regard to batteries included vs. not, I think it makes sense for sufficiently common patterns. But I also think first-class examples in the docs can go a long way here. If we can get this bidirectional, I think a special section in the docs about βadvanced serializationβ might be merited and/or suffice.
I donβt know much about protobuf but I feel like there might be a similar way to achieve support for it (though it might require more substantial feature requests, at least to pydantic). That could offer even bigger improvements to the serialization.
On Sat, 14 Sep, 2019, 23:01 dmontagu, ***@***.***> wrote:
@sandys <https://github.com/sandys> yes, it doesnβt handle that yet. That
could probably be done via middleware, though I donβt know how easy
starlette makes it. Iβll see if I can figure it out.
I donβt know much about protobuf but I feel like there might be a similar
way to achieve support for it (though it might require more substantial
feature requests, at least to pydantic). That could offer even bigger
improvements to the serialization.
β
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#521>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AAASYUZXCEDTNGX5E4NKZJLQJUNVNANCNFSM4IVUIA7A>
.
@sandys I ended up having to go back to the older implementation to get it to work. I did have to make use of a private API on the request to replace its body (to prepare it to be consumed by pydantic). This could be handled without the override of the body, but it would involve a small change to a very long method in fastapi, somewhere near this line: https://github.com/tiangolo/fastapi/blob/580cf8f4e2aac3d4f298fbb3ca1426f9ea6265de/fastapi/routing.py#L93
I opted for the small change to a short(er) method instead.
This approach has the benefit of not adding extra routes to be matched.
Let me know if this implementation works for you.
Going through this actually also revealed to me another good feature request for FastAPI: the ability to easily override the way the self.app is generated in the route class. This would make it easier to add header-specific route behavior by using a subclass of APIRoute. I'll throw together some PRs that would reduce the amount of custom code involved, but even if nothing is accepted the above example should still work for you.
It is monkey patched by replacing the linked function with modifications at noted above. As we are patching internal functions you will need to update the patch every version of FastAPI.
Okay, for anyone who follows, this is the code I was able to get working on fastapi 0.88.0, following @jcsaaddupuy. Note the custom request was not included, because @jcsaaddupuy does not seem to work any more. For some reason, a msgpack request confuses fastapi's typing machinery and it throws an error.
Also, @dgasmith , this approach did not require any monkey patching. Though I suspect it may be brittle for relying on the internals of fastapi...
changed the title [-][FEATURE] msgpack response if client asks for application/x-msgpack[/-][+]msgpack response if client asks for application/x-msgpack[/+]on Feb 24, 2023
Activity
dmontagu commentedon Sep 12, 2019
@sandys
I think fastapi may actually be relatively well suited to handle this now without modifications.
If your top priority is just reducing bandwidth usage, I think it should be straightforward to implement converting the json responses to msgpack (in the presence of the appropriate mimetype request) as an ASGI middleware. I imagine that would involve parsing the json and dumping it to msgpack format, so would come with some processing overhead. But that overhead would probably be negligible compared to network, especially if bandwidth is the source of the concern.
If you really want to avoid the reparsing, I think this would also be possible by creating a custom starlette response that holds the python dict you want to serialize (rather than encoded json), and adding a middleware that converts responses of that type to a new starlette.Response with msgpack-encoded contents.
If you are serious about this and want/need a little more guidance than provided above, I can put together more of a skeleton implementation.
dmontagu commentedon Sep 12, 2019
This might be even easier than I thought.
I'd suggest taking a look at
starlette.responses.JSONResponse-- it looks like you could pretty easily create aMsgpackResponseby defining an appropriaterenderfunction (e.g., usingmsgpack-python). Then, you could have your endpoints returnmsgpack-encoded data by settingresponse_class=MsgpackResponse. That wouldn't allow for dynamic determination of the response type based on the request, but maybe there is still a way to achieve that...(Certainly, in the worst case, you could just perform a reparsing of the
JSONResponsein a middleware.)dmontagu commentedon Sep 12, 2019
@sandys
Actually, I got interested in this and was able to throw together a working example -- not quite how I expected it would need to go, and it has some hacks that could probably be removed (maybe would require a feature request or two), but it works:
sandys commentedon Sep 13, 2019
dmontagu commentedon Sep 13, 2019
@sandys
I've reworked it to be substantially simpler, and also I've put some thought into what first-class support could/should look like in FastAPI.
Here's a msgpack-specific simplified implementation (with minimal docs) that runs as is to show how simple it is:
(note
include_both_serialization_routescould be removed with a relatively minor feature request, described below).Click to expand
Next, here's a more general implementation that might be worthy of first-class support (note: it should run as is if you copy/paste):
Click to expand
Discussion of appropriate feature requests
Getting this "built in" would probably require the following two feature requests:
(I think it is unlikely that fastapi would add this directly, but I suppose it's possible.)
Given how short it is, I expect it may be better not to upstream it, and have to deal with the additional testing burden, etc.
@sandys is this what you had in mind for having the client specify the mimetype? One might want to parse the accept header into a list of strings, but this works for now.
This function could be removed if fastapi supported
route_classparameter in APIRouter.include_router. I personally think this is a reasonable feature request that should be added.With the above feature requests, even without built-in support for msgpack, the ultimate usage would be as simple as:
@sandys Would this be good enough for you to consider it as being supported in a "first class" way? If not, is there anything specific you don't like, or think is missing?
Edit: I suppose it would be good to add support for receiving msgpack payloads as well; this would probably need to be done in a middleware.
dmontagu commentedon Sep 14, 2019
Rereading your original comment, I think I see more explicitly what you are looking for:
I didn't think about the idea that this would just be handled by default for all apps. I think this could be done inside FastAPI using an approach similar to that proposed above, and could be an option to enable if msgpack is present. But I don't know if it's worth the additional maintenance burden on fastapi; I don't know how commonly used this serialization format is (especially compared to JSON).
@tiangolo If I had to guess, I would assume that this feature request is outside the scope of what you'd want to support out of the box. But if that's wrong, let me know and I can take a stab at a PR incorporating this directly into FastAPI.
sandys commentedon Sep 14, 2019
@dmontagu i would like to again add a million thanks to the work you have done above. I do not think i would have been able to figure this stuff out without putting weeks into it...and maybe still not (or would have given up).
And that is a good context to why this is important. I come from the Rails world and I frequently read about how big sites use Rails (e.g. here) . The key to observe here is "batteries included" but not linked to the batteries.
For example in Rails you can skip all the "batteries included" functionality by opt-out. Rails is opt-in by default ...and that is what im asking Fastapi devs to consider.
rails new app_name --skip-action-cable --skip-action-textFastapi is quickly becoming more than just a wrapper on top of starlette. And that is a tradeoff between functionality versus simplicity (and even performance). For example Starlette still beats Fastapi on performance, but for a developer, there is no question which he will choose. It may come as no surprise that most people start with https://github.com/tiangolo/full-stack-fastapi-postgresql . I personally would not have been able to begin with Fastapi if i didnt have that starter readymade.
I think (and I really hope) that Fastapi keeps adding batteries , which are skippable. Because i know for sure - that without you writing the code above, there was an almost zero chance that I would have achieved it myself in time.
sandys commentedon Sep 14, 2019
however, i do so the reluctance devs may have to tie it to msgpack at this point. Fair enough - however i would really request for you to put in the code that enables MsgpackResponse and MsgpackRoute. That would be a superb help to add new mimetypes and response serialization formats
sandys commentedon Sep 14, 2019
@dmontagu your code doesnt work both ways right ? it doesnt accept msgpack data in the request. In Asia, the big bottlenecks is when data is sent from mobile devices (which is 90% of all internet devices) to the server.
dmontagu commentedon Sep 14, 2019
@sandys yes, it doesnβt handle that yet. That could probably be done via middleware, though I donβt know how easy starlette makes it. Iβll see if I can figure it out.
With regard to batteries included vs. not, I think it makes sense for sufficiently common patterns. But I also think first-class examples in the docs can go a long way here. If we can get this bidirectional, I think a special section in the docs about βadvanced serializationβ might be merited and/or suffice.
I donβt know much about protobuf but I feel like there might be a similar way to achieve support for it (though it might require more substantial feature requests, at least to pydantic). That could offer even bigger improvements to the serialization.
sandys commentedon Sep 14, 2019
sandys commentedon Sep 16, 2019
@dmontagu any chance you were able to look at request middleware ? didnt want to bother you, but keeping my fingers crossed.
P.S. just for msgpack as an example ..not for anything else (like protobuf, etc that we were discussing).
dmontagu commentedon Sep 16, 2019
Haven't yet, but I still intend to. I'm pretty busy right now but ping again in a couple days if you don't hear back.
dmontagu commentedon Sep 17, 2019
@sandys I ended up having to go back to the older implementation to get it to work. I did have to make use of a private API on the request to replace its body (to prepare it to be consumed by pydantic). This could be handled without the override of the body, but it would involve a small change to a very long method in fastapi, somewhere near this line:
https://github.com/tiangolo/fastapi/blob/580cf8f4e2aac3d4f298fbb3ca1426f9ea6265de/fastapi/routing.py#L93
I opted for the small change to a short(er) method instead.
This approach has the benefit of not adding extra routes to be matched.
Let me know if this implementation works for you.
Going through this actually also revealed to me another good feature request for FastAPI: the ability to easily override the way the
self.appis generated in the route class. This would make it easier to add header-specific route behavior by using a subclass of APIRoute. I'll throw together some PRs that would reduce the amount of custom code involved, but even if nothing is accepted the above example should still work for you.60 remaining items
swamidass commentedon Dec 29, 2022
Oh I see that this involved some updates to fastapi that were actually merged to source, right? So it isn't actually monkey patched, per se.
If I am understanding this correctly, does it mean now that using a the MessagePack asgi middle ware should work now?
Also, it seems that some of the example code you posted in the past does not work in the current version of fastapi (0.88.0). #521 (comment)
dgasmith commentedon Dec 29, 2022
It is monkey patched by replacing the linked function with modifications at noted above. As we are patching internal functions you will need to update the patch every version of FastAPI.
swamidass commentedon Dec 30, 2022
Okay, for anyone who follows, this is the code I was able to get working on fastapi 0.88.0, following @jcsaaddupuy. Note the custom request was not included, because @jcsaaddupuy does not seem to work any more. For some reason, a msgpack request confuses fastapi's typing machinery and it throws an error.
Also, @dgasmith , this approach did not require any monkey patching. Though I suspect it may be brittle for relying on the internals of fastapi...
[-][FEATURE] msgpack response if client asks for application/x-msgpack[/-][+]msgpack response if client asks for application/x-msgpack[/+]github-actions commentedon Feb 28, 2023
Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.