Skip to content

Advanced Middleware

JustAPI supports any ASGI middleware:

from justapi import JustAPIApp
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = JustAPIApp()
app.add_middleware(HTTPSRedirectMiddleware)

Guard against HTTP host header attacks:

app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["example.com", "*.example.com"],
)
from starlette.middleware.gzip import GZipMiddleware
app.add_middleware(GZipMiddleware, minimum_size=500, compresslevel=9)

Write your own middleware class:

import time
from starlette.middleware.base import BaseHTTPMiddleware
class TimingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
start = time.time()
response = await call_next(request)
duration = time.time() - start
response.headers["X-Process-Time"] = str(round(duration, 4))
return response
app.add_middleware(TimingMiddleware)