python
53 lines · 9 steps
Custom gzip middleware in FastAPI
A middleware that compresses responses with gzip only when the client accepts it and the body is large enough.
Explained by
highlit
1import gzip
2from fastapi import FastAPI, Request, Response
3from starlette.middleware.base import BaseHTTPMiddleware
4from starlette.types import ASGIApp
5
6
7class ConditionalGZipMiddleware(BaseHTTPMiddleware):
8 def __init__(
9 self,
10 app: ASGIApp,
11 minimum_size: int = 1024,
12 compress_level: int = 6,
13 ) -> None:
14 super().__init__(app)
15 self.minimum_size = minimum_size
16 self.compress_level = compress_level
17
18 async def dispatch(self, request: Request, call_next) -> Response:
19 response = await call_next(request)
20
21 accepted = request.headers.get("accept-encoding", "")
22 if "gzip" not in accepted.lower():
23 return response
24
25 if response.headers.get("content-encoding"):
26 return response
27
28 body = b"".join([chunk async for chunk in response.body_iterator])
29
30 if len(body) < self.minimum_size:
31 return Response(
32 content=body,
33 status_code=response.status_code,
34 headers=dict(response.headers),
35 media_type=response.media_type,
36 )
37
38 compressed = gzip.compress(body, compresslevel=self.compress_level)
39 headers = dict(response.headers)
40 headers["content-encoding"] = "gzip"
41 headers["content-length"] = str(len(compressed))
42 headers["vary"] = "Accept-Encoding"
43
44 return Response(
45 content=compressed,
46 status_code=response.status_code,
47 headers=headers,
48 media_type=response.media_type,
49 )
50
51
52app = FastAPI()
53app.add_middleware(ConditionalGZipMiddleware, minimum_size=2048)
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Subclassing BaseHTTPMiddleware lets you inspect and rewrite responses around the whole request cycle.
- 2Content negotiation means honoring the client's Accept-Encoding before applying any transformation.
- 3Compressing tiny payloads wastes CPU, so a minimum-size threshold keeps the optimization worthwhile.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/custom-gzip-middleware-in-fastapi-explained-python-55dc/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.