|
1 | | -import datetime |
2 | | -import logging |
3 | | -import os |
4 | 1 |
|
5 | | -from fastapi import FastAPI |
6 | | -from fastapi.middleware.cors import CORSMiddleware |
7 | | -from fastapi.responses import JSONResponse |
8 | | - |
9 | | -from .backoffice import router as backoffice_router |
10 | | -from .routers import operator |
11 | | -from .utils.logging import setup_logging |
12 | | - |
13 | | -# Configuración constantes |
14 | | -APP_NAME = "NeuroBank FastAPI Toolkit" |
15 | | -APP_VERSION = "1.0.0" |
16 | | -APP_DESCRIPTION = """ |
17 | | -## 🏦 NeuroBank FastAPI Toolkit |
18 | | -
|
19 | | -**Professional banking operations API** with enterprise-grade features and **admin backoffice dashboard**: |
20 | | -
|
21 | | -### 🚀 Key Features |
22 | | -- **Banking Operations**: Comprehensive account management and transactions |
23 | | -- **Admin Dashboard**: Visual backoffice panel at `/backoffice/` with real-time metrics |
24 | | -- **Security First**: API key authentication and request validation |
25 | | -- **Production Ready**: AWS serverless deployment with monitoring |
26 | | -- **High Performance**: Async operations with optimized response times |
27 | | -
|
28 | | -### 🎨 Backoffice Dashboard |
29 | | -- **Real-time Metrics**: Live transaction monitoring and system health |
30 | | -- **Interactive Charts**: Chart.js visualizations for business intelligence |
31 | | -- **Transaction Management**: Advanced filtering and administration tools |
32 | | -- **Responsive Design**: Bootstrap 5 with professional banking UI |
33 | | -- **Protected Admin Panels**: Secure administrative access |
34 | | -
|
35 | | -### 🛠️ Technical Stack |
36 | | -- **FastAPI**: Modern, fast web framework for building APIs |
37 | | -- **Jinja2**: Template engine for dynamic HTML generation |
38 | | -- **Bootstrap 5**: Professional UI framework with responsive design |
39 | | -- **Chart.js**: Interactive data visualizations |
40 | | -- **Pydantic**: Data validation using Python type annotations |
41 | | -- **AWS Lambda**: Serverless compute platform |
42 | | -- **CloudWatch**: Monitoring and logging |
43 | | -
|
44 | | -### 📚 API Documentation |
45 | | -- **Swagger UI**: Available at `/docs` (interactive documentation) |
46 | | -- **ReDoc**: Available at `/redoc` (alternative documentation) |
47 | | -- **Admin Dashboard**: Available at `/backoffice/` (visual interface) |
48 | | -
|
49 | | -### 🔐 Authentication |
50 | | -All endpoints require a valid API key in the `X-API-Key` header. |
51 | | -
|
52 | | -### 📊 Health Monitoring |
53 | | -- Health check endpoint at `/health` |
54 | | -- Comprehensive logging with structured JSON format |
55 | | -- CloudWatch integration for production monitoring |
56 | | -
|
57 | | ---- |
58 | | -*Built with ❤️ for modern banking infrastructure* |
59 | | -""" |
60 | | - |
61 | | -# Configurar logging |
62 | | -setup_logging() |
63 | | -logger = logging.getLogger(__name__) |
64 | | - |
65 | | -# Crear la aplicación FastAPI con documentación mejorada |
66 | | -app = FastAPI( |
67 | | - title=APP_NAME, |
68 | | - description=APP_DESCRIPTION, |
69 | | - version=APP_VERSION, |
70 | | - docs_url="/docs", |
71 | | - redoc_url="/redoc", |
72 | | - contact={ |
73 | | - "name": "NeuroBank Development Team", |
74 | | - |
75 | | - }, |
76 | | - license_info={ |
77 | | - "name": "MIT License", |
78 | | - "url": "https://opensource.org/licenses/MIT", |
79 | | - }, |
80 | | - servers=[ |
81 | | - {"url": "https://api.neurobank.com", "description": "Production server"}, |
82 | | - {"url": "https://staging-api.neurobank.com", "description": "Staging server"}, |
83 | | - {"url": "http://localhost:8000", "description": "Development server"}, |
84 | | - ], |
85 | | -) |
86 | | - |
87 | | -# Configurar CORS - usando configuración de Railway |
88 | | -from .config import get_settings |
89 | | - |
90 | | -settings = get_settings() |
91 | | - |
92 | | -app.add_middleware( |
93 | | - CORSMiddleware, |
94 | | - allow_origins=settings.cors_origins, |
95 | | - allow_credentials=True, |
96 | | - allow_methods=["GET", "POST", "PUT", "DELETE"], |
97 | | - allow_headers=["*"], |
98 | | -) |
99 | | - |
100 | | -# Incluir routers |
101 | | -app.include_router(operator.router, prefix="/api", tags=["api"]) |
102 | | -app.include_router(backoffice_router.router, tags=["backoffice"]) |
103 | | - |
104 | | - |
105 | | -# Health check endpoint |
106 | | -@app.get( |
107 | | - "/health", |
108 | | - summary="🏥 Health Check", |
109 | | - description="Comprehensive health check endpoint for monitoring service status", |
110 | | - response_description="Service health status with detailed information", |
111 | | - tags=["Health & Monitoring"], |
112 | | - responses={ |
113 | | - 200: { |
114 | | - "description": "Service is healthy and operational", |
115 | | - "content": { |
116 | | - "application/json": { |
117 | | - "example": { |
118 | | - "status": "healthy", |
119 | | - "service": "NeuroBank FastAPI Toolkit", |
120 | | - "version": "1.0.0", |
121 | | - "timestamp": "2025-07-20T15:30:45.123456Z", |
122 | | - "environment": "production", |
123 | | - "uptime_seconds": 3600, |
124 | | - } |
125 | | - } |
126 | | - }, |
127 | | - } |
128 | | - }, |
129 | | -) |
130 | | -async def health_check(): |
131 | | - """ |
132 | | - **Endpoint de verificación de salud del sistema** |
133 | | -
|
134 | | - Retorna información detallada sobre: |
135 | | - - ✅ Estado del servicio |
136 | | - - 📊 Versión actual |
137 | | - - ⏰ Timestamp de respuesta |
138 | | - - 🌍 Entorno de ejecución |
139 | | - - ⏱️ Tiempo de actividad |
140 | | -
|
141 | | - **Casos de uso:** |
142 | | - - Monitoreo automatizado (Kubernetes, Docker, AWS) |
143 | | - - Load balancers health checks |
144 | | - - Verificación de deployments |
145 | | - - Debugging y troubleshooting |
146 | | - """ |
147 | | - import datetime |
148 | | - import os |
149 | | - |
150 | | - return JSONResponse( |
151 | | - status_code=200, |
152 | | - content={ |
153 | | - "status": "healthy", |
154 | | - "service": APP_NAME, |
155 | | - "version": APP_VERSION, |
156 | | - "timestamp": f"{datetime.datetime.now(datetime.timezone.utc).isoformat()}", |
157 | | - "environment": os.getenv("ENVIRONMENT", "production"), |
158 | | - "railway": { |
159 | | - "project_name": os.getenv("RAILWAY_PROJECT_NAME", "unknown"), |
160 | | - "project_id": os.getenv("RAILWAY_PROJECT_ID", "unknown"), |
161 | | - "service_name": os.getenv("RAILWAY_SERVICE_NAME", "unknown"), |
162 | | - "environment_name": os.getenv("RAILWAY_ENVIRONMENT_NAME", "unknown"), |
163 | | - "private_domain": os.getenv("RAILWAY_PRIVATE_DOMAIN", "unknown"), |
164 | | - }, |
165 | | - "uptime_seconds": "N/A", # Se puede implementar con un contador global |
166 | | - }, |
167 | | - ) |
168 | | - |
169 | | - |
170 | | -# Root endpoint |
171 | | -@app.get( |
172 | | - "/", |
173 | | - summary="🏠 API Root", |
174 | | - description="Welcome endpoint with API information and navigation links", |
175 | | - response_description="API overview with quick navigation", |
176 | | - tags=["Information"], |
177 | | - responses={ |
178 | | - 200: { |
179 | | - "description": "API information and navigation links", |
180 | | - "content": { |
181 | | - "application/json": { |
182 | | - "example": { |
183 | | - "message": "Welcome to NeuroBank FastAPI Toolkit", |
184 | | - "version": "1.0.0", |
185 | | - "status": "operational", |
186 | | - "documentation": {"swagger_ui": "/docs", "redoc": "/redoc"}, |
187 | | - "endpoints": { |
188 | | - "health_check": "/health", |
189 | | - "operator_operations": "/operator", |
190 | | - }, |
191 | | - "features": [ |
192 | | - "🏦 Banking Operations", |
193 | | - "🔐 API Key Authentication", |
194 | | - "📊 Real-time Monitoring", |
195 | | - "☁️ AWS Serverless Ready", |
196 | | - ], |
197 | | - } |
198 | | - } |
199 | | - }, |
200 | | - } |
201 | | - }, |
202 | | -) |
203 | | -async def root(): |
204 | | - """ |
205 | | - **Endpoint de bienvenida de la API** |
206 | | -
|
207 | | - Proporciona información general sobre la API incluyendo: |
208 | | - - 📋 Información básica del servicio |
209 | | - - 🔗 Enlaces de navegación rápida |
210 | | - - 📚 Acceso a documentación |
211 | | - - ⚡ Estado operacional |
212 | | - - 🎯 Características principales |
213 | | -
|
214 | | - **Útil para:** |
215 | | - - Verificación rápida de conectividad |
216 | | - - Descubrimiento de endpoints principales |
217 | | - - Validación de versión de API |
218 | | - - Navegación inicial para desarrolladores |
219 | | - """ |
220 | | - return { |
221 | | - "message": f"Welcome to {APP_NAME}", |
222 | | - "version": APP_VERSION, |
223 | | - "status": "operational", |
224 | | - "documentation": {"swagger_ui": "/docs", "redoc": "/redoc"}, |
225 | | - "endpoints": {"health_check": "/health", "operator_operations": "/operator"}, |
226 | | - "features": [ |
227 | | - "🏦 Banking Operations", |
228 | | - "🔐 API Key Authentication", |
229 | | - "📊 Real-time Monitoring", |
230 | | - "☁️ AWS Serverless Ready", |
231 | | - ], |
232 | | - } |
233 | | - |
234 | | - |
235 | | -if __name__ == "__main__": |
236 | | - import uvicorn |
237 | | - import uvloop |
238 | | - |
239 | | - # Use uvloop for better performance |
240 | | - uvloop.install() |
241 | | - |
242 | | - port = int(os.getenv("PORT", 8000)) |
243 | | - workers = int(os.getenv("WORKERS", 1)) # Single worker for Railway |
244 | | - |
245 | | - uvicorn.run( |
246 | | - "app.main:app", |
247 | | - host="0.0.0.0", |
248 | | - port=port, |
249 | | - workers=workers, |
250 | | - loop="uvloop", |
251 | | - access_log=True, |
252 | | - timeout_keep_alive=120, |
253 | | - ) |
0 commit comments