Enterprise-grade climate risk assessment API with real-time data processing and analysis
RESTful API | Asynchronous | Production Ready | Secure by Default
Features β’ Installation β’ API Documentation β’ Architecture β’ Security β’ Contributing
A robust, scalable API for assessing climate-related risks, built with FastAPI and SQLAlchemy 2.0. This service provides endpoints for managing locations, weather data, and risk assessments with support for real-time data processing and analysis.
-
Location Management
- Store and retrieve geographical locations
- Geocoding and reverse geocoding support
- Spatial queries for proximity-based searches
-
Weather Data
- Historical weather data storage and retrieval
- Weather forecasts integration
- Weather condition tracking
-
Risk Assessment
- Multi-factor risk scoring
- Historical risk analysis
- Vulnerability assessment
-
Security & Performance
- β JWT-based authentication
- π Role-based access control
- π‘οΈ Rate limiting and request throttling
- π API versioning support
- π Comprehensive request/response logging
- π Optimized for high performance
-
Developer Experience
- π Comprehensive API documentation
- β Type hints and static type checking
- π§ͺ Test coverage
- π CI/CD ready
- π³ Docker support
- Python 3.10+
- PostgreSQL 13+ (or SQLite for development)
- Redis (for rate limiting and caching)
- Docker (optional, for containerized deployment)
-
Clone the repository:
git clone https://github.com/yourusername/climate-risk-api.git cd climate-risk-api -
Create and activate a virtual environment:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies:
pip install -e ".[dev]" -
Configure environment variables:
cp .env.example .env # Edit .env with your configuration -
Initialize the database:
alembic upgrade head
-
Run the development server:
# Development (auto-reload) uvicorn src.app:app --reload # Production # uvicorn src.app:app --host 0.0.0.0 --port 8000 --workers 4
-
Or run with Docker Compose (recommended for production):
docker-compose up -d --build
climate-risk-api/
βββ alembic/ # Database migrations
βββ src/
β βββ climate_risk/ # Main application package
β β βββ application/ # Application services
β β βββ domain/ # Domain models and interfaces
β β βββ infrastructure/ # Database and external service implementations
β β βββ interfaces/ # API endpoints and web interface
β βββ app.py # FastAPI application entry point
βββ tests/ # Test suite
βββ .env.example # Example environment variables
βββ pyproject.toml # Project dependencies and configuration
βββ README.md # This file
Once the application is running, you can access the following documentation:
- Swagger UI: http://localhost:8000/api/v1/docs
- ReDoc: http://localhost:8000/api/v1/redoc
- OpenAPI Schema: http://localhost:8000/api/v1/openapi.json
TheAPI uses semantic versioning (e.g., v1.0.0). You can specify the API version in multiple ways:
- URL Path:
/api/v1/endpoint - Header:
Accept: application/vnd.api.v1+json - Query Parameter:
/api/endpoint?version=1 - Cookie:
api-version=1
The API includes several security features:
- Default: 100 requests per minute per IP
- Configurable via environment variables
- Supports Redis for distributed rate limiting
- Content Security Policy (CSP)
- X-Content-Type-Options
- X-Frame-Options
- X-XSS-Protection
- HSTS (HTTP Strict Transport Security)
- Referrer-Policy
- Permissions-Policy
- JWT-based authentication
- Role-based access control (RBAC)
- Secure password hashing
- Token refresh mechanism
- Structured JSON logging
- Request/response logging
- Sensitive data redaction
- Correlation IDs for request tracing
- Health check endpoint (
/health) - Metrics endpoint (
/metrics) - Performance monitoring
- Error tracking
- Python 3.10+ - Core programming language
- FastAPI - Web framework for building APIs
- SQLAlchemy 2.0 - ORM for database interactions
- Alembic - Database migrations
- Pydantic - Data validation and settings management
- JWT - Authentication
- Redis - Rate limiting and caching
- Uvicorn - ASGI server
- Gunicorn - Production WSGI server
- Passlib - Password hashing
- python-jose - JWT implementation
- python-multipart - File uploads
- email-validator - Email validation
- Pandas - Data manipulation
- NumPy - Numerical computing
- GeoPandas - Geospatial data
- Shapely - Geometric operations
- pytest - Testing framework
- pytest-cov - Test coverage
- black - Code formatting
- isort - Import sorting
- mypy - Static type checking
- ruff - Linting
- pre-commit - Git hooks
- mypy - Static type checking
- bandit - Security linting
- safety - Dependency vulnerability scanning
# Build the image
docker build -t climate-risk-api .
# Run the container
docker run -d --name climate-risk-api -p 8000:8000 --env-file .env climate-risk-api# Example deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: climate-risk-api
spec:
replicas: 3
selector:
matchLabels:
app: climate-risk-api
template:
metadata:
labels:
app: climate-risk-api
spec:
containers:
- name: climate-risk-api
image: your-registry/climate-risk-api:latest
ports:
- containerPort: 8000
envFrom:
- secretRef:
name: climate-risk-secrets
resources:
limits:
cpu: "1"
memory: "1Gi"
requests:
cpu: "100m"
memory: "256Mi"
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 5
periodSeconds: 5Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- FastAPI community for the amazing framework
- SQLAlchemy for the powerful ORM
- All contributors who have helped improve this project
# Clone repository
git clone https://github.com/yourusername/climate-risk-api.git
cd climate-risk-api
cd climate-risk-assessment
# Create virtual environment
python -m venv venv
source venv/bin/activate # Linux/Mac
.\venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
# Set up environment variables
export WEATHER_API_KEY='your_key_here'
export ML_MODEL_PATH='path/to/models'from climate_risk import RiskAssessment
# Initialize assessment tool
risk_tool = RiskAssessment(config_path='config.yaml')
# Run analysis
results = risk_tool.analyze_region(
latitude=40.7128,
longitude=-74.0060,
time_horizon='7d'
)
# Generate report
risk_tool.generate_report(results, output_dir='reports')graph TD
A[Weather Data] --> B[Data Processing]
B --> C[Feature Engineering]
C --> D[ML Models]
D --> E[Risk Assessment]
E --> F[Recommendations]
- Ensemble Methods
- Voting Classifier
- Stacking Regressor
- Model Averaging
- Deep Learning
- LSTM Networks
- Attention Mechanisms
- Transfer Learning
| Model | Accuracy | Precision | Recall | F1-Score |
|---|---|---|---|---|
| Ensemble | 96.5% | 0.95 | 0.97 | 0.96 |
| LSTM | 94.3% | 0.93 | 0.95 | 0.94 |
| XGBoost | 93.8% | 0.92 | 0.94 | 0.93 |
# Create feature branch
git checkout -b feature/new-feature
# Run tests
pytest tests/
coverage run -m pytest
# Build documentation
sphinx-build -b html docs/source docs/buildclass RiskAssessment:
"""
Main interface for climate risk assessment.
Features:
- Real-time data integration
- Multi-model predictions
- Uncertainty estimation
"""- Improved future update ouline in changelog
- Added a better health impact integration
- Refined climate science validation module
- Added a test module
- Refactored project structure into
Core,data, andutilsmodules - Improved real-time data fetching and processing
- Enhanced model training and management with versioning
- Added comprehensive risk scoring and confidence estimation
- Improved visualization capabilities with Plotly
- Added health impact analysis module
- Improved logging and configuration management
- Improved future update outline in changelog
- Added a better health impact integration
- Refined Climate Science Validation
- Added a test module
- Initial release with basic ML models and risk assessment capabilities
- Add climate model ensemble integration
- Implement uncertainty quantification
- Add demographic vulnerability factors
- Include ecosystem impact assessment
- Add extreme event attribution analysis
- Add scientific methodology documentation
- Include model validation metrics
- Add climate science references
- Document health impact methodologies
- Fork repository
- Create feature branch
- Commit changes
- Push to branch
- Create Pull Request
MIT License - see LICENSE
| Role | Name | Contact |
|---|---|---|
| Lead Developer | Yan Cotta | yanpcotta@gmail.com |
| Issues | - | GitHub Issues |
- Weather data providers
- Climate science community
- Open source contributors