Website · Docs · Playground · Dashboard · Discord
Production-ready security middleware for FastAPI.
IP filtering, rate limiting, signature-based attack-pattern detection, and 20+ per-route security decorators.
📋 Using this in production?Tell me what is working and what is not → Six minutes. It decides what gets built next. |
📊 State of FastAPI Security 2026Five minutes, nothing to sign up for. |
Quick Start
uv add fastapi-guard # uv (recommended)
pip install fastapi-guard # pip
poetry add fastapi-guard # poetry
Example
from fastapi import FastAPI
from guard import SecurityMiddleware, SecurityConfig
app = FastAPI()
config = SecurityConfig(
enable_rate_limiting=True,
rate_limit=100,
rate_limit_window=60,
enable_ip_banning=True,
auto_ban_threshold=5,
auto_ban_duration=86400,
custom_log_file="security.log",
enforce_https=True,
enable_cors=True,
cors_allow_origins=["*"],
cors_allow_methods=["GET", "POST"],
cors_allow_headers=["*"],
cors_allow_credentials=True,
cors_expose_headers=["X-Custom-Header"],
cors_max_age=600,
block_cloud_providers={"AWS", "GCP", "Azure"},
)
app.add_middleware(SecurityMiddleware, config=config)
For production, wire guard.lifespan.guard_lifespan into FastAPI(lifespan=...) so initialization runs at app startup instead of on the first request, see Eager initialization.
A connection with no client address (a Unix domain socket, some serverless ASGI adapters) is rejected with 403 by default (fail_secure=True); set fail_secure=False to run the pipeline with identity "unknown" instead, allowed unless a whitelist or a country allow-list is configured (blacklist, country, and cloud checks cannot match without an address; detection and the shared rate-limit bucket still apply). Add the literal string "unix" to trusted_proxies to resolve the real client from X-Forwarded-For on such a connection, see Proxy Security.
SecurityMiddleware protects HTTP requests only; it never runs for WebSocket connections. Secure a @app.websocket route explicitly with Depends(guard_websocket), see WebSockets.
Per-Route Security Decorators
Apply security rules at the endpoint level with composable decorators:
from guard import SecurityConfig, SecurityDecorator
config = SecurityConfig(
auth_verifier=lambda request, credential: {"user": "demo"} if credential else None,
)
guard = SecurityDecorator(config)
@app.get("/api/payments")
@guard.require_auth(type="bearer")
@guard.rate_limit(requests=10, window=60)
@guard.block_countries(["CN", "RU"])
@guard.require_https()
async def process_payment():
return {"status": "ok"}
require_auth and api_key_auth require a verifier (per-route verifier= or global SecurityConfig.auth_verifier); without one the request is rejected with 401. For a presence-only Authorization header gate, use require_authorization_header(scheme="bearer") instead. See the authentication tutorial for the full migration.
Available decorator categories:
- Access ---
require_ip,block_countries,allow_countries,block_clouds,bypass - Auth ---
require_https,require_auth,api_key_auth,require_headers - Rate Limiting ---
rate_limit,geo_rate_limit - Content ---
block_user_agents,content_type_filter,max_request_size,require_referrer,custom_validation,detection_exclusion - Behavioral ---
usage_monitor,return_monitor,suspicious_frequency,behavior_analysis - Advanced ---
time_window,honeypot_detection,suspicious_detection
Cloud Dashboard
FastAPI Guard has a centralized cloud platform for real-time monitoring and threat analysis across all your applications.
- Dashboard --- real-time security events, threat intelligence, attack pattern analytics
- Playground --- try every security feature in-browser with real attack data from a live server
- Dynamic Rules --- update security configuration from the dashboard without redeploying
- GDPR Tools --- consent management, data export, account deletion
uv add guard-agent # or: pip install guard-agent
from fastapi import FastAPI
from guard import SecurityConfig, SecurityMiddleware
security_config = SecurityConfig(
enable_agent=True,
agent_api_key="your-api-key",
agent_endpoint="https://api.guard-core.com",
agent_project_id="your-project-id",
agent_buffer_size=100,
agent_flush_interval=2,
agent_enable_events=True,
agent_enable_metrics=True,
enable_dynamic_rules=True,
dynamic_rule_interval=60,
)
app = FastAPI()
app.add_middleware(SecurityMiddleware, config=security_config)
That is the entire integration. The middleware drives the agent's lifecycle for you --- do not import guard_agent, construct an AgentConfig, or wire a lifespan hook when using fastapi-guard; doing so spins up a second agent that never sees traffic.
Free tier includes 10,000 events/month --- no credit card required.
The core library is fully self-contained and MIT licensed. The cloud dashboard is optional.
Monitoring agent buffer health
When enable_agent=True, the middleware exposes an agent_stats property that returns the current buffer drop counters and transport circuit-breaker state without needing to reach into the agent directly:
middleware: SecurityMiddleware = ...
stats = middleware.agent_stats
{"enabled": True, "buffer_stats": {"events_dropped": 0, "metrics_dropped": 0, ...},
"transport_stats": {"circuit_breaker_state": "CLOSED", ...}, ...}
When the agent is disabled or failed to initialize, the property returns {"enabled": False}. Read it on each scrape; it reflects live counters and is not cached.
Ecosystem
Guard Core is the Python engine. Framework adapters are thin wrappers that translate native request/response types into Guard Core's protocols. The telemetry agents ship security events and metrics to the monitoring backend. Parallel engine implementations exist for Go, PHP, TypeScript (on npm), and Rust (on crates.io) - all ports of the same reference semantics, conformance-tested against the shared adversarial corpus.
Python
| Package | Role | PyPI |
|---|---|---|
| guard-core | Framework-agnostic security engine | |
| guard-agent | Telemetry agent |
|
| fastapi-guard | FastAPI / Starlette adapter |
|
| flaskapi-guard | Flask adapter |
|
| djapi-guard | Django adapter |
|
| tornadoapi-guard | Tornado adapter |
|
Go
Go modules published via GitHub releases. Production-ready.
| Package | Role | Release |
|---|---|---|
| guard-core-go | Go engine | |
| nethttp-guard | net/http adapter |
|
| gin-guard | Gin adapter |
|
| echo-guard | Echo (v4) adapter |
|
| fiber-guard | Fiber (v3) adapter |
|
| guard-agent-go | Telemetry agent |
|
PHP
Published on Packagist under the rennf93 vendor. Production-ready.
| Package | Role | Packagist |
|---|---|---|
| guard-core-php | PHP engine | |
| laravel-guard | Laravel adapter |
|
| symfony-guard | Symfony adapter |
|
| psr15-guard | PSR-15 adapter |
|
| slim-guard | Slim 4 adapter |
|
| guard-agent-php | Telemetry agent |
|
TypeScript / JavaScript
Published under the @guardcore npm scope; source in the guard-core-ts monorepo. Production-ready.
| Package | Role | npm |
|---|---|---|
| | @guardcore/core | Core engine | |
| @guardcore/express | Express adapter |
|
| @guardcore/nestjs | NestJS adapter |
|
| @guardcore/fastify | Fastify adapter |
|
| @guardcore/hono | Hono (edge) adapter |
|
| guardagent | Telemetry agent |
|
Rust
Published on crates.io. Production-ready.
| Package | Role | crates.io |
|---|---|---|
| guard-core-engine | Core engine crate | |
| guard-core-rs | Facade crate (consumer entry point) |
|
| actix-guard-rs | Actix Web adapter |
|
| axum-guard-rs | Axum adapter |
|
| tower-guard-rs | Tower adapter |
|
| rocket-guard-rs | Rocket adapter |
|
| guard-agent-rs | Telemetry agent |
|
AI Coding Agents
| Package | Role | PyPI |
|---|---|---|
| guard-core-mcp | MCP server: config validation, docs search, detection sandbox | |
Documentation
- Installation
- First Steps
- Configuration Reference
- Decorator Reference
- API Reference
- Example App
- Redis Integration
Contributing
Contributions are welcome. See CONTRIBUTING.md for guidelines.
New security features (checks, detection patterns, handlers) should be contributed to guard-core. This repo covers the FastAPI/Starlette adapter layer.
License
This project is licensed under the MIT License. See the LICENSE file for details.
