DEV Community

Gealber Morales
Gealber Morales

Posted on • Updated on • Originally published at

Gzip Middleware recipe for FastAPI

Originally published on my blog

Not a full and long article, but a hacking recipe to process incoming Gzipped requests. This example is with FastAPI, but could be used as well with Starlette applications.

from fastapi import FastAPI
from starlette.types import Message
from starlette.requests import Request
from starlette.middleware.base import BaseHTTPMiddleware
import gzip          

class GZipedMiddleware(BaseHTTPMiddleware):
    async def set_body(self, request: Request):
        receive_ = await request._receive()
        if "gzip" in request.headers.getlist("Content-Encoding"):
            data = gzip.decompress(receive_.get('body'))
            receive_['body'] = data

        async def receive() -> Message:
            return receive_

        request._receive = receive                

    async def dispatch(self, request, call_next):
        await self.set_body(request)        
        response = await call_next(request)                
        return response

app = FastAPI()

async def post(req: Request):
    body = await req.body()
    # I decode here, assuming that I just compressed
    # a text file, in other use case you should use
    # the appropiate decoder.
    return body.decode("utf-8")

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

nlile profile image

Isn't this already baked in with

from starlette.middleware.gzip import GZipMiddleware?

__masashi__ profile image

It is there. Gealber showed us how it worked internally.