| title | description | keywords |
|---|---|---|
Getting Started with FastAPI Guard |
First steps guide for implementing FastAPI Guard security features in your FastAPI application |
fastapi security tutorial, fastapi guard setup, python security middleware |
Let's start with a simple example that shows how to add FastAPI Guard to your application.
First, create a new FastAPI application:
from fastapi import FastAPI
from guard.middleware import SecurityMiddleware
from guard.models import SecurityConfig
from guard.handlers.ipinfo_handler import IPInfoManager
app = FastAPI()Create a SecurityConfig instance with your desired settings:
config = SecurityConfig(
geo_ip_handler=IPInfoManager("your_ipinfo_token_here"), # NOTE: Required for geolocation
db_path="data/ipinfo/country_asn.mmdb", # Optional, default: ./data/ipinfo/country_asn.mmdb
enable_redis=True, # Enable Redis integration
redis_url="redis://localhost:6379", # Redis URL
rate_limit=100, # Max requests per minute
auto_ban_threshold=5, # Ban after 5 suspicious requests
custom_log_file="security.log" # Custom log file
)Note: FastAPI Guard only loads resources as needed. The IPInfo database is only downloaded when country filtering is configured, and cloud IP ranges are only fetched when cloud provider blocking is enabled.
Add the security middleware to your application:
app.add_middleware(SecurityMiddleware, config=config)Here's a complete example showing basic usage:
from fastapi import FastAPI
from guard.middleware import SecurityMiddleware
from guard.models import SecurityConfig
from guard.handlers.ipinfo_handler import IPInfoManager
app = FastAPI()
config = SecurityConfig(
geo_ip_handler=IPInfoManager("your_ipinfo_token_here"),
enable_redis=True, # Redis enabled
redis_url="redis://localhost:6379",
whitelist=["192.168.1.1", "2001:db8::1"],
blacklist=["10.0.0.1", "2001:db8::2"],
blocked_countries=["AR", "IT"],
rate_limit=100,
custom_log_file="security.log"
)
app.add_middleware(SecurityMiddleware, config=config)
@app.get("/")
async def root():
return {"message": "Hello World"}Run your application using uvicorn:
uvicorn main:app --reloadYour API is now protected by FastAPI Guard! 🛡️
- Learn about IP Management
- Configure Rate Limiting
- Set up Penetration Detection
- Learn about Redis Integration