Skip to main content

FastAPI Guard

PyPI version License: MIT CI Release CodeQL Downloads

Website · Docs · Playground · Dashboard · Discord

Guard Core badge

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.
Anonymous unless you choose otherwise.

📊 State of FastAPI Security 2026

Take the survey →

Five minutes, nothing to sign up for.
Results published publicly, free for everyone.


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.


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

Full decorator reference


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

Connect your existing setup in 2 minutes:

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

FastAPI Guard is built on guard-core, a framework-agnostic security engine. The same protection is available across Python, TypeScript, and Rust.

Python

Package Role PyPI
guard-core Framework-agnostic security engine PyPI
guard-agent Telemetry agent PyPI
fastapi-guard FastAPI / Starlette adapter (this package) PyPI
flaskapi-guard Flask adapter PyPI
djapi-guard Django adapter PyPI
tornadoapi-guard Tornado adapter PyPI

TypeScript / JavaScript

Published under the @guardcore npm scope. Source in the guard-core-ts monorepo. Production-ready.

Package Role npm
@guardcore/core Core engine npm
@guardcore/express Express adapter npm
@guardcore/nestjs NestJS adapter npm
@guardcore/fastify Fastify adapter npm
@guardcore/hono Hono adapter npm

Rust

Published on crates.io. 🚧 Placeholder crates: implementation in progress.

Package Role crates.io
guard-core Core engine crates.io
actix-guard-rs Actix adapter crates.io
axum-guard-rs Axum adapter crates.io
rocket-guard-rs Rocket adapter crates.io
tower-guard-rs Tower adapter crates.io

AI Coding Agents

Package Role PyPI
guard-core-mcp MCP server: config validation, docs search, detection sandbox PyPI

An MCP server that answers questions about FastAPI Guard from the version installed in your project, rather than from a model's memory of it. It validates a config against the real SecurityConfig model (catching silently-ignored typos like redis_failopen), looks up any field's type, default and description, searches the bundled docs, and runs a payload through the real detection engine to show whether it would be blocked and by which pattern.

uv add --dev guard-core-mcp
claude mcp add guard-core -- uv run guard-core-mcp

Install it into the same environment as FastAPI Guard; it introspects what is actually installed there, so an isolated run (uvx) has nothing to read.


Documentation


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.


Author

Renzo Franceschini

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_guard-7.7.0.tar.gz (52.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_guard-7.7.0-py3-none-any.whl (27.1 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_guard-7.7.0.tar.gz.

File metadata

  • Download URL: fastapi_guard-7.7.0.tar.gz
  • Upload date:
  • Size: 52.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.10.21

File hashes

Hashes for fastapi_guard-7.7.0.tar.gz
Algorithm Hash digest
SHA256 7fd033109878b87bd3c83b3ee1cbe65839e9f43ddd12171595dfed6467fa03be
MD5 54b12a8914e3493e4d97ffa571330913
BLAKE2b-256 b7b9b3bc3b33f2f4ebcf4d9a660a66871b0d3b62fd5364d55ad06112ab3a7b10

See more details on using hashes here.

File details

Details for the file fastapi_guard-7.7.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_guard-7.7.0-py3-none-any.whl
  • Upload date:
  • Size: 27.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.10.21

File hashes

Hashes for fastapi_guard-7.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 061d67d8b678a4a42d0f34f7d53dd726b6c9da8a944bc8cc386b6ea81009b05e
MD5 a1652a7c5c9094361b5d93289b1f98e0
BLAKE2b-256 2f26a2d8b8e78a391b73e5fa992c70dc749fc120f1da1b130cf57b2e2ed6be0a

See more details on using hashes here.

Release history Release notifications | RSS feed

8.0.0

2 files

7.8.2

2 files

7.8.1

2 files

7.8.0

2 files

This release

7.7.0 This release

2 files

7.6.0

2 files

7.5.1

2 files

7.5.0

2 files

7.4.1

2 files

7.4.0

2 files

7.3.1

2 files

7.3.0

2 files

7.2.2

2 files

7.2.1

2 files

7.2.0

2 files

7.1.1

2 files

7.1.0

2 files

7.0.0

2 files

6.0.0

2 files

5.2.0

2 files

5.1.1

2 files

5.1.0

2 files

5.0.0

2 files

4.4.1

2 files

4.4.0

2 files

4.3.1

2 files

4.3.0

2 files

4.2.2

2 files

4.2.1

2 files

4.2.0

2 files

4.1.2

2 files

4.1.0

2 files

4.0.3

2 files

4.0.2

2 files

4.0.1

2 files

3.0.2

2 files

3.0.1

2 files

3.0.0

2 files

2.1.3

2 files

2.1.2

2 files

2.1.1

2 files

2.1.0

2 files

2.0.1

2 files

2.0.0

2 files

1.5.0

2 files

1.4.0

2 files

1.3.2

2 files

1.2.2

2 files

1.2.1

2 files

1.2.0

2 files

1.1.0

2 files

1.0.0

2 files

0.4.0

2 files

0.3.4

2 files

0.3.3

2 files

0.3.2

2 files

0.2.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page