- Add ConfigLoader class for loading RateLimitConfig and GlobalConfig - Support .env files with FASTAPI_TRAFFIC_* prefixed variables - Support JSON configuration files with type validation - Add convenience functions: load_rate_limit_config, load_global_config - Add load_rate_limit_config_from_env, load_global_config_from_env - Support custom environment variable prefixes - Add comprehensive error handling with ConfigurationError - Add 47 tests for configuration loading - Add example 11_config_loader.py with 9 usage patterns - Update examples/README.md with config loader documentation - Update CHANGELOG.md with new feature - Fix typo in limiter.py (errant 'fi' on line 4)
171 lines
4.2 KiB
Markdown
171 lines
4.2 KiB
Markdown
# FastAPI Traffic Examples
|
|
|
|
This directory contains comprehensive examples demonstrating how to use the `fastapi-traffic` rate limiting library.
|
|
|
|
## Basic Examples
|
|
|
|
### 01_quickstart.py
|
|
|
|
Minimal setup to get rate limiting working. Start here if you're new to the library.
|
|
|
|
- Basic backend and limiter setup
|
|
- Exception handler for rate limit errors
|
|
- Simple decorator usage
|
|
|
|
### 02_algorithms.py
|
|
|
|
Demonstrates all available rate limiting algorithms:
|
|
|
|
- **Fixed Window** - Simple, resets at fixed intervals
|
|
- **Sliding Window** - Most precise, stores timestamps
|
|
- **Sliding Window Counter** - Balance of precision and efficiency (default)
|
|
- **Token Bucket** - Allows controlled bursts
|
|
- **Leaky Bucket** - Smooths out traffic
|
|
|
|
### 03_backends.py
|
|
|
|
Shows different storage backends:
|
|
|
|
- **MemoryBackend** - Fast, ephemeral (default)
|
|
- **SQLiteBackend** - Persistent, single-instance
|
|
- **RedisBackend** - Distributed, multi-instance
|
|
|
|
### 04_key_extractors.py
|
|
|
|
Custom key extractors for different rate limiting strategies:
|
|
|
|
- Rate limit by IP address (default)
|
|
- Rate limit by API key
|
|
- Rate limit by user ID
|
|
- Rate limit by endpoint + IP
|
|
- Rate limit by tenant/organization
|
|
- Composite keys (user + action)
|
|
|
|
### 05_middleware.py
|
|
|
|
Middleware-based rate limiting for global protection:
|
|
|
|
- Basic middleware setup
|
|
- Custom configuration options
|
|
- Path and IP exemptions
|
|
- Alternative middleware classes
|
|
|
|
## Advanced Examples
|
|
|
|
### 06_dependency_injection.py
|
|
|
|
Using FastAPI's dependency injection system:
|
|
|
|
- Basic rate limit dependency
|
|
- Tier-based rate limiting
|
|
- Combining multiple rate limits
|
|
- Conditional exemptions
|
|
|
|
### 07_redis_distributed.py
|
|
|
|
Redis backend for distributed deployments:
|
|
|
|
- Multi-instance rate limiting
|
|
- Shared counters across nodes
|
|
- Health checks and statistics
|
|
- Fallback to memory backend
|
|
|
|
### 08_tiered_api.py
|
|
|
|
Production-ready tiered API example:
|
|
|
|
- Free, Starter, Pro, Enterprise tiers
|
|
- Different limits per tier
|
|
- Feature gating based on tier
|
|
- API key validation
|
|
|
|
### 09_custom_responses.py
|
|
|
|
Customizing rate limit responses:
|
|
|
|
- Custom JSON error responses
|
|
- Logging/monitoring callbacks
|
|
- Different response formats (JSON, HTML, plain text)
|
|
- Rate limit headers
|
|
|
|
### 10_advanced_patterns.py
|
|
|
|
Real-world patterns and use cases:
|
|
|
|
- **Cost-based limiting** - Different operations cost different amounts
|
|
- **Priority exemptions** - Premium users exempt from limits
|
|
- **Resource-based limiting** - Limit by resource ID + user
|
|
- **Login protection** - Brute force prevention
|
|
- **Webhook limiting** - Protect external services
|
|
- **Request fingerprinting** - Spam prevention
|
|
- **Time-of-day limits** - Peak vs off-peak hours
|
|
- **Cascading limits** - Per-second, per-minute, per-hour
|
|
|
|
### 11_config_loader.py
|
|
|
|
Loading configuration from external files:
|
|
|
|
- **Environment variables** - Load from `FASTAPI_TRAFFIC_*` env vars
|
|
- **.env files** - Load from dotenv files for local development
|
|
- **JSON files** - Load from JSON for structured configuration
|
|
- **Custom prefixes** - Use custom env var prefixes
|
|
- **Validation** - Automatic type validation and error handling
|
|
- **Environment-based config** - Different configs for dev/staging/prod
|
|
|
|
Run with `--demo` flag to see all configuration examples:
|
|
|
|
```bash
|
|
python examples/11_config_loader.py --demo
|
|
```
|
|
|
|
## Running Examples
|
|
|
|
Each example is a standalone FastAPI application. Run with:
|
|
|
|
```bash
|
|
# Using uvicorn directly
|
|
uvicorn examples.01_quickstart:app --reload
|
|
|
|
# Or run the file directly
|
|
python examples/01_quickstart.py
|
|
```
|
|
|
|
## Testing Rate Limits
|
|
|
|
Use curl or httpie to test:
|
|
|
|
```bash
|
|
# Basic request
|
|
curl http://localhost:8000/api/basic
|
|
|
|
# With API key
|
|
curl -H "X-API-Key: my-key" http://localhost:8000/api/by-api-key
|
|
|
|
# Check rate limit headers
|
|
curl -i http://localhost:8000/api/data
|
|
|
|
# Rapid requests to trigger rate limit
|
|
for i in {1..20}; do curl http://localhost:8000/api/basic; done
|
|
```
|
|
|
|
## Environment Variables
|
|
|
|
Some examples support configuration via environment variables:
|
|
|
|
- `RATE_LIMIT_BACKEND` - Backend type (memory, sqlite, redis)
|
|
- `REDIS_URL` - Redis connection URL for distributed examples
|
|
|
|
## Requirements
|
|
|
|
Basic examples only need `fastapi-traffic` and `uvicorn`:
|
|
|
|
```bash
|
|
pip install fastapi-traffic uvicorn
|
|
```
|
|
|
|
For Redis examples:
|
|
|
|
```bash
|
|
pip install redis
|
|
```
|