Starlette Compress

1.7.0 · active · verified Tue Apr 14

Starlette Compress is a fast and simple ASGI middleware for Starlette and FastAPI applications that provides response compression. It supports Zstandard (Zstd), Brotli, and GZip algorithms and offers more sensible defaults compared to Starlette's built-in GZipMiddleware. Currently at version 1.7.0, the library is actively maintained and aims for semantic versioning compliance.

Warnings

Install

Imports

Quickstart

This example demonstrates how to integrate `CompressMiddleware` into a Starlette application. The middleware automatically compresses responses based on the client's `Accept-Encoding` header, provided the response meets the minimum size requirement.

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.responses import PlainTextResponse
from starlette.routing import Route
from starlette_compress import CompressMiddleware

async def homepage(request):
    return PlainTextResponse("This is a sample response that will be compressed if larger than 500 bytes.")

routes = [
    Route("/", endpoint=homepage),
]

middleware = [
    Middleware(CompressMiddleware, minimum_size=100) # Set a lower minimum_size for demonstration
]

app = Starlette(routes=routes, middleware=middleware)

# To run this example, save it as app.py and execute: uvicorn app:app --port 8000
# Then test with curl -H "Accept-Encoding: gzip, deflate, br, zstd" http://localhost:8000/

view raw JSON →