How do I add InjectShield middleware to FastAPI?
The recommended pattern is FastAPI middleware on every endpoint that forwards user content into an LLM. Two files.
injectshield_middleware.py:
from fastapi import Request, HTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from injectshield import Client
shield = Client()
class InjectShieldMiddleware(BaseHTTPMiddleware): LLM_ROUTES = {"/chat", "/agent", "/rag"} async def dispatch(self, request, call_next): if request.url.path in self.LLM_ROUTES and request.method == "POST": body = await request.body() text = extract_user_text(body) # your parsing v = shield.classify(text, context="user", mode="hybrid") if v.verdict == "injection": raise HTTPException(400, {"error":"prompt_injection_blocked","categories":v.categories}) request.state.injection_verdict = v # log downstream return await call_next(request) ```
main.py: app.add_middleware(InjectShieldMiddleware).
This single middleware covers user-input injection (OWASP LLM01 direct). For full coverage, also wrap your LLM call site to scan tool outputs (context: "tool_output") and retrieved RAG chunks (context: "document") — middleware is the wrong layer for those because they originate inside your handler, not on the request.
For async-heavy endpoints, the InjectShield Python client supports async/await and connection pooling — the typical added latency is 1-3 ms for heuristic-only and 100-200 ms for hybrid mode. Add OpenTelemetry/Datadog tracing on request.state.injection_verdict for SIEM integration. Reference repo at injectshield.dev/docs/fastapi.