Skip to main content

Production-ready security middleware for FastAPI — IP filtering, rate limiting, penetration detection, and 20+ per-route security decorators.

Project description

FastAPI Guard

PyPI version License: MIT CI Release CodeQL Downloads

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.


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=30,
    rate_limit_window=60,
    enable_ip_banning=True,
    auto_ban_threshold=5,
    auto_ban_duration=86400,
    custom_log_file="security.log",
    rate_limit=100,
    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)

Per-Route Security Decorators

Apply security rules at the endpoint level with composable decorators:

from guard import SecurityConfig, SecurityDecorator

config = SecurityConfig()
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"}

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
  • 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 collections.abc import AsyncGenerator
from contextlib import asynccontextmanager

from fastapi import FastAPI
from guard import SecurityConfig, SecurityMiddleware
from guard_agent import AgentConfig, guard_agent

security_config = SecurityConfig(
    enable_agent=True,
    agent_api_key="your-api-key",
    agent_endpoint="https://api.guard-core.com/api/v1",
    agent_project_id="your-project-id",
    agent_buffer_size=5000,
    agent_flush_interval=2,
    agent_enable_events=True,
    agent_enable_metrics=True,
    enable_dynamic_rules=True,
    dynamic_rule_interval=60,
)

agent_config = AgentConfig(
    api_key="your-api-key",
    endpoint="https://api.guard-core.com/api/v1",
    project_id="your-project-id",
    buffer_size=5000,
    flush_interval=2,
)

agent = guard_agent(agent_config)


@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncGenerator[None]:
    await agent.start()
    yield
    await agent.stop()


app = FastAPI(lifespan=lifespan)
app.add_middleware(SecurityMiddleware, config=security_config)

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

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

Project details


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.0.0.tar.gz (15.3 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.0.0-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for fastapi_guard-7.0.0.tar.gz
Algorithm Hash digest
SHA256 67dcd1a562dfef4d98093e3fe4f8f11909278d8c907df1b119dc5ad7c1aea418
MD5 55d17f5755d5d98a906d33390622bacf
BLAKE2b-256 35774a4da5dc6d477f8f33bd4628960be26feb62d3ebd32d649cf6316c70c943

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for fastapi_guard-7.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9f80f0f95d49081431f2949b91e6d94f8d864860eb474028ec43a1bd22f21730
MD5 70f64b30c86697e2f8acdc7afd03bf20
BLAKE2b-256 2923f453f7401d64887fbfa96456739fbae300e7bfeda48fdcda4129ac7eee35

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page