Starlette Compress
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
- gotcha Responses must be at least 500 bytes by default to be compressed. This is an optimization to prevent CPU overhead for minimal bandwidth savings. If you expect smaller responses to be compressed, adjust the `minimum_size` parameter.
- gotcha Default compression levels are set to 4 for all algorithms. Higher levels result in smaller files but require more CPU and time, while lower levels are faster but produce larger files. Tune these based on your performance and bandwidth needs.
- gotcha The middleware compresses a predefined set of content-types. If your application serves custom content-types (e.g., `application/x-my-format`), they will not be compressed by default. You must explicitly add them.
- gotcha Running `starlette-compress` alongside another compression middleware (e.g., Starlette's built-in `GZipMiddleware`, an ASGI server's compression, or another framework's middleware) can lead to double compression, which is inefficient and may cause errors or corrupted responses.
- gotcha By default, the `Accept-Encoding` header remains intact after `starlette-compress` has processed the request. This can sometimes lead to issues if downstream middleware or the application itself attempts to re-negotiate or apply further compression based on this header.
- breaking Starlette, the underlying framework for `starlette-compress`, now requires Python 3.9+ for versions 1.0.0 and above. While `starlette-compress` also requires Python 3.9+, older Starlette applications on Python 3.8 or earlier will break when upgrading Starlette, potentially impacting `starlette-compress` compatibility.
Install
-
pip install starlette-compress
Imports
- CompressMiddleware
from starlette_compress import CompressMiddleware
Quickstart
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/