Brotli ASGI Middleware

1.6.0 · active · verified Tue Apr 14

brotli-asgi is an ASGI middleware that provides Brotli response compression for ASGI applications like Starlette and FastAPI. It offers faster and more dense compression than GZip, making it a drop-in replacement for the GZipMiddleware. As of v1.6.0, it remains actively maintained with periodic updates for dependencies and occasional feature enhancements.

Warnings

Install

Imports

Quickstart

This example demonstrates how to integrate `BrotliMiddleware` with a FastAPI application. The middleware is added globally, applying Brotli compression to responses that meet the specified criteria (e.g., minimum size). It also configures a gzip fallback for clients that don't support Brotli.

from fastapi import FastAPI
from brotli_asgi import BrotliMiddleware
from starlette.responses import JSONResponse

app = FastAPI()

app.add_middleware(
    BrotliMiddleware,
    quality=4,        # Compression quality (0-11, higher is slower but denser)
    mode="text",      # Compression mode: "generic", "text", or "font"
    minimum_size=400, # Only compress responses larger than this many bytes
    gzip_fallback=True # Fallback to gzip if 'br' is not in Accept-Encoding
)

@app.get("/")
async def home():
    return JSONResponse({"data": "a" * 4000})

# To run this example, you would typically use uvicorn:
# uvicorn your_module_name:app --reload

view raw JSON →