DEV Community

Gealber Morales
Gealber Morales

Posted on • Edited on • Originally published at gealber.com

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"):
            print(receive_)                                     
            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()

app.add_middleware(GZipedMiddleware)


@app.post("/post")
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)

Collapse
 
nlile profile image
Nathan

Isn't this already baked in with

from starlette.middleware.gzip import GZipMiddleware?

Collapse
 
__masashi__ profile image
Masashi

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