Skip to content

msgpack response if client asks for application/x-msgpackΒ #521

Closed

Description

@sandys

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.

msgpack is very important for Asia which are highly internet bandwidth constrained. We are prepared to tradeoff speed in exchange for lesser bandwidth (e.g. http://indiegamr.com/cut-your-data-exchange-traffic-by-up-to-50-with-one-line-of-code-msgpack-vs-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.

msgpack is fairly production ready. Lots of downstream python libraries use it in production - https://github.com/0rpc/zerorpc-python

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

Activity

  1. added
    feature
    on Sep 11, 2019
  2. dmontagu commented on Sep 12, 2019

    @dmontagu
    Contributor

    @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.

  3. dmontagu commented on Sep 12, 2019

    @dmontagu
    Contributor

    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 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.)

  4. dmontagu commented on Sep 12, 2019

    @dmontagu
    Contributor

    @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:

    from typing import Any, Dict, List, Type
    
    import msgpack
    from fastapi import FastAPI
    from fastapi.routing import APIRoute, get_app
    from starlette.background import BackgroundTask
    from starlette.requests import Request
    from starlette.responses import JSONResponse, Response
    from starlette.routing import request_response
    from 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 = "Accept"
        default_response_class = JSONResponse
        response_class_map: Dict[str, Type[Response]] = {"application/x-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
            self._status_code = status_code
            self._media_type = media_type
            self._background = background
            self.init_headers(headers)
    
        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'
  5. sandys commented on Sep 13, 2019

    @sandys
    Author
  6. dmontagu commented on Sep 13, 2019

    @dmontagu
    Contributor

    @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_routes could be removed with a relatively minor feature request, described below).

    Click to expand
        from typing import Any, List, Tuple
    
        import msgpack
        from fastapi import FastAPI, APIRouter
        from fastapi.routing import APIRoute
        from starlette.requests import Request
        from starlette.responses import JSONResponse
        from starlette.routing import Match
        from starlette.testclient import TestClient
        from starlette.types import Scope
    
        class MsgpackResponse(JSONResponse):
            media_type = "application/x-msgpack"
    
            def render(self, content: Any) -> bytes:
                return msgpack.packb(content)
    
        class MsgpackRoute(APIRoute):
            detection_header = "Accept"
            detection_header_match = "appliaction/x-msgpack"
            response_class_mapping = {JSONResponse: MsgpackResponse}
            include_in_schema_override = False
    
            def __init__(self, *args: Any, **kwargs: Any) -> None:
                include_in_schema = kwargs["include_in_schema"] if self.include_in_schema_override is None else None
                response_class = self.response_class_mapping.get(kwargs["response_class"], kwargs["response_class"])
                kwargs["include_in_schema"] = include_in_schema
                kwargs["response_class"] = response_class
                super().__init__(*args, **kwargs)
    
            def matches(self, scope: Scope) -> Tuple[Match, Scope]:
                if not Request(scope).headers.get(self.detection_header) == self.detection_header_match:
                    return Match.NONE, {}
                return super().matches(scope)
    
        def include_both_serialization_routes(
            parent_router: APIRouter, include_router: APIRouter
        ) -> None:
            original_route_class = parent_router.route_class
            parent_router.route_class = MsgpackRoute
            parent_router.include_router(include_router)
            parent_router.route_class = original_route_class
            parent_router.include_router(include_router)
    
        router = APIRouter()
        @router.get("/", response_model=List[int])
        async def root():
            return [1, 2, 3]
    
        app = FastAPI()
        include_both_serialization_routes(app.router, router)
        client = TestClient(app)
    
        print(client.get("/", headers={"Accept": "application/x-msgpack"}).content)
        # b'\x93\x01\x02\x03'
    
        print(client.get("/").content)
        # b'[1,2,3]'

    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
        from typing import Any, List, Optional, ClassVar, get_type_hints, Tuple, Type
        
        import msgpack
        from fastapi import FastAPI, APIRouter
        from fastapi.routing import APIRoute
        from starlette.requests import Request
        from starlette.responses import JSONResponse
        from starlette.routing import Match
        from starlette.testclient import TestClient
        from starlette.types import Scope
        
        class MsgpackResponse(JSONResponse):
            media_type = "application/x-msgpack"
        
            def render(self, content: Any) -> bytes:
                return msgpack.packb(content)
        
        class OverrideResponseClassRoute(APIRoute):
            detection_header: ClassVar[str]
            detection_header_match: ClassVar[str]
            response_class_mapping: ClassVar[JSONResponse]
            include_in_schema_override: ClassVar[Optional[bool]] = None
        
            def __init_subclass__(cls) -> None:
                missing_attributes: List[str] = []
                for attribute in get_type_hints(OverrideResponseClassRoute):
                    if not hasattr(cls, attribute):
                        missing_attributes.append(attribute)
                if missing_attributes:
                    raise TypeError(f"{cls.__name__} did not define the following attributes: {missing_attributes}")
        
            def __init__(self, *args: Any, **kwargs: Any) -> None:
                include_in_schema = kwargs["include_in_schema"] if self.include_in_schema_override is None else None
                response_class = self.response_class_mapping.get(kwargs["response_class"], kwargs["response_class"])
        
                kwargs["include_in_schema"] = include_in_schema
                kwargs["response_class"] = response_class
        
                super().__init__(*args, **kwargs)
        
            def matches(self, scope: Scope) -> Tuple[Match, Scope]:
                if not Request(scope).headers.get(self.detection_header) == self.detection_header_match:
                    return Match.NONE, {}
                return super().matches(scope)
        
        class MsgpackRoute(OverrideResponseClassRoute):
            detection_header = "Accept"
            detection_header_match = "application/x-msgpack"
            response_class_mapping = {JSONResponse: MsgpackResponse}
            include_in_schema_override = False
        
        def include_typed_router(
            parent_router: APIRouter, include_router: APIRouter, *, route_class: Optional[Type[APIRoute]] = None
        ) -> None:
            original_route_class = parent_router.route_class
            parent_router.route_class = route_class or original_route_class
            try:
                parent_router.include_router(include_router)
            finally:
                parent_router.route_class = original_route_class
        
        router = APIRouter()
        @router.get("/", response_model=List[int])
        async def root():
            return [1, 2, 3]
    
        app = FastAPI()
        include_typed_router(app.router, router, route_class=MsgpackRoute)
        include_typed_router(app.router, router)
        client = TestClient(app)
        
        print(client.get("/", headers={"Accept": "application/x-msgpack"}).content)
        # b'\x93\x01\x02\x03'
        
        print(client.get("/").content)
        # b'[1,2,3]'

    Discussion of appropriate feature requests

    class MsgpackResponse(JSONResponse):
        media_type = "application/x-msgpack"
    
        def render(self, content: Any) -> bytes:
            return msgpack.packb(content)

    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.


    class OverrideResponseClassRoute(APIRoute):
        detection_header: ClassVar[str]
        detection_header_match: ClassVar[str]
        response_class_mapping: ClassVar[JSONResponse]
        include_in_schema_override: ClassVar[Optional[bool]] = None
    
        def __init_subclass__(cls) -> None:
            missing_attributes: List[str] = []
            for attribute in get_type_hints(OverrideResponseClassRoute):
                if not hasattr(cls, attribute):
                    missing_attributes.append(attribute)
            if missing_attributes:
                raise TypeError(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"] if self.include_in_schema_override is None else None
            response_class = self.response_class_mapping.get(kwargs["response_class"], kwargs["response_class"])
    
            kwargs["include_in_schema"] = include_in_schema
            kwargs["response_class"] = response_class
    
            super().__init__(*args, **kwargs)
    
        def matches(self, scope: Scope) -> Tuple[Match, Scope]:
            if not Request(scope).headers.get(self.detection_header) == self.detection_header_match:
                return Match.NONE, {}
            return super().matches(scope)
    
    class MsgpackRoute(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.


    def include_typed_router(
        parent_router: APIRouter, include_router: APIRouter, *, route_class: Optional[Type[APIRoute]] = None
    ) -> None:
        original_route_class = parent_router.route_class
        parent_router.route_class = route_class or original_route_class
        try:
            parent_router.include_router(include_router)
        finally:
            parent_router.route_class = original_route_class

    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:

    # ###################
    # ##### msgpack #####
    # ###################
    class MsgpackResponse(JSONResponse):
        media_type = "application/msgpack"
        def render(self, content: Any) -> bytes:
            return msgpack.packb(content)
    
    class MsgpackRoute(OverrideResponseClassRoute):
        detection_header = "Accept"
        detection_header_match = "application/x-msgpack"
        response_class_mapping = {JSONResponse: MsgpackResponse}
        include_in_schema_override = False
    # ###################
    
    router = APIRouter()
    @router.get("/", response_model=List[int])
    async def root():
        return [1, 2, 3]
    
    app = FastAPI()
    app.include_router(router, route_class=MsgpackRoute)
    app.include_router(router)

    @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.

  7. dmontagu commented on Sep 14, 2019

    @dmontagu
    Contributor

    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.

  8. sandys commented on Sep 14, 2019

    @sandys
    Author

    @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.

  9. sandys commented on Sep 14, 2019

    @sandys
    Author

    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

  10. sandys commented on Sep 14, 2019

    @sandys
    Author

    @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.

  11. dmontagu commented on Sep 14, 2019

    @dmontagu
    Contributor

    @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.

  12. sandys commented on Sep 14, 2019

    @sandys
    Author
  13. sandys commented on Sep 16, 2019

    @sandys
    Author

    @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).

  14. dmontagu commented on Sep 16, 2019

    @dmontagu
    Contributor

    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.

  15. dmontagu commented on Sep 17, 2019

    @dmontagu
    Contributor

    @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.

    import json
    from typing import Any, Optional, Type, Dict
    
    import msgpack
    from starlette.requests import Request
    from starlette.responses import JSONResponse, Response
    from starlette.routing import request_response
    from starlette.testclient import TestClient
    
    from fastapi import FastAPI, APIRouter
    from fastapi.encoders import jsonable_encoder
    from fastapi.routing import APIRoute, get_app
    
    
    class MsgpackResponse(JSONResponse):
        media_type = "application/x-msgpack"
    
        def render(self, content: Any) -> bytes:
            return msgpack.packb(content)
    
    
    class MsgpackRoute(APIRoute):
        def __init__(self, *args: Any, **kwargs: Any) -> None:
            super().__init__(*args, **kwargs)
            original_app = 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(request: Request) -> Response:
                if request.headers.get("Content-Type") == "application/x-msgpack":
                    body = await request.body()
                    request._body = json.dumps(jsonable_encoder(msgpack.loads(body))).encode()
                response = await original_app(request)
                if request.headers.get("Accept") == "application/x-msgpack":
                    return MsgpackResponse(content=json.loads(response.body))
                return response
    
            self.app = request_response(app)
    
    
    def include_typed_router(
        parent_router: APIRouter, include_router: APIRouter, *, route_class: Optional[Type[APIRoute]] = None
    ) -> None:
        original_route_class = parent_router.route_class
        parent_router.route_class = route_class or original_route_class
        try:
            parent_router.include_router(include_router)
        finally:
            parent_router.route_class = original_route_class
    
    
    router = APIRouter()
    
    
    @router.post("/")
    async def root(body: Dict[str, Any]):
        return body
    
    
    app = FastAPI()
    include_typed_router(app.router, router, route_class=MsgpackRoute)
    client = TestClient(app)
    
    input = {"a": [1, 2, 3], "b": "c"}
    msgpack_out_response = client.post("/", json=input, headers={"Accept": "application/x-msgpack"}).content
    print(msgpack_out_response)
    # b'\x82\xa1a\x93\x01\x02\x03\xa1b\xa1c'
    assert jsonable_encoder(msgpack.loads(msgpack_out_response)) == input
    
    msgpack_in_response = client.post(
        "/", data=msgpack_out_response, headers={"Content-Type": "application/x-msgpack"}
    ).content
    print(msgpack_in_response)
    # b'{"a":[1,2,3],"b":"c"}'
    assert json.loads(msgpack_in_response) == input

    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.

  16. 60 remaining items

  17. swamidass commented on Dec 29, 2022

    @swamidass

    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)

  18. dgasmith commented on Dec 29, 2022

    @dgasmith

    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.

  19. swamidass commented on Dec 30, 2022

    @swamidass

    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...

    
    import typing as t
    import json
    import msgpack
    from fastapi import FastAPI
    from fastapi.routing import APIRoute, get_request_handler
    from starlette.requests import Request
    from starlette.responses import Response
    
    from starlette.routing import request_response
    from starlette.testclient import TestClient
    
    class MsgpackResponse(Response):
        media_type = "application/x-msgpack"
    
        def render(self, content: t.Any) -> bytes:
            return msgpack.packb(content)
    
    class MsgpackRoute(APIRoute):
        ROUTES_HANDLERS_CLASSES = {MsgpackResponse.media_type: MsgpackResponse}
    
        def _get_media_type_route_handler(self, media_type):
            return get_request_handler(
                dependant=self.dependant,
                body_field=self.body_field,
                status_code=self.status_code,
                # use custom response class or fallback on default self.response_class
                response_class=self.ROUTES_HANDLERS_CLASSES.get(
                    media_type, 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_exclude_unset=self.response_model_exclude_unset,
                response_model_exclude_defaults=self.response_model_exclude_defaults,
                response_model_exclude_none=self.response_model_exclude_none,
                dependency_overrides_provider=self.dependency_overrides_provider,
            )
    
        def get_route_handler(self) -> t.Callable:
            async def custom_route_handler(request: Request) -> Response:
                accept = request.headers.get("Accept")
                route_handler = self._get_media_type_route_handler(accept)
                return await route_handler(request)
    
            return custom_route_handler
    
    
    app = FastAPI()
    app.router.route_class = MsgpackRoute
    
    @app.post("/")
    async def root(body : dict):
        return body
    
    
    client = TestClient(app)
    
    input = {"a": [1, 2, 3], "b": "c"}
    response = client.post("/", json=input, headers={"Accept": "application/x-msgpack"})
    msgpack_out_response = response.content
    print(msgpack_out_response)
    # b'\x82\xa1a\x93\x01\x02\x03\xa1b\xa1c'
    assert msgpack.loads(msgpack_out_response) == input
    
    
    input = {"a": [1, 2, 3], "b": "c"}
    response = client.post("/", json=input, headers={"Accept": "application/json"})
    json_out_response = response.content
    print(json_out_response)
    # b'{"a":[1,2,3],"b":"c"}'
    
    assert json.loads(json_out_response) == input
    
  20. added
    question
    and removed
    feature
    on Feb 23, 2023
  21. 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
  22. github-actions commented on Feb 28, 2023

    @github-actions
    Contributor

    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.

  23. locked and limited conversation to collaborators on Feb 28, 2023
  24. converted this issue into a discussion #8065 on Feb 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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