from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html from fastapi.openapi.utils import get_openapi from fastapi.staticfiles import StaticFiles import os from loguru import logger import time import uvicorn from api.routers import spam_router, health_router from api.core.config import settings from api.core.exceptions import CustomException app = FastAPI( title=settings.PROJECT_NAME, description=settings.PROJECT_DESCRIPTION, version=settings.PROJECT_VERSION, openapi_url=None if settings.ENVIRONMENT == "production" else "/openapi.json" ) # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.CORS_ORIGINS], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Register routers app.include_router(health_router.router, tags=["Health"]) app.include_router(spam_router.router, prefix="/api/v1", tags=["Spam Classification"]) # Mount static files app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "static")), name="static") # Custom exception handler @app.exception_handler(CustomException) async def custom_exception_handler(request: Request, exc: CustomException): return JSONResponse( status_code=exc.status_code, content={"detail": exc.detail, "error_code": exc.error_code} ) # Middleware for request logging @app.middleware("http") async def log_requests(request: Request, call_next): start_time = time.time() # Get the client IP forwarded = request.headers.get("X-Forwarded-For") ip = forwarded.split(",")[0] if forwarded else ( request.client.host if request.client is not None else "127.0.0.1" ) # Log the request logger.info(f"Request: {request.method} {request.url.path} from {ip}") response = await call_next(request) # Calculate processing time process_time = time.time() - start_time logger.info(f"Response: {request.method} {request.url.path} - Status: {response.status_code}, Time: {process_time:.4f}s") # Add custom header with processing time response.headers["X-Process-Time"] = str(process_time) return response # Custom OpenAPI schema with additional metadata @app.get("/openapi.json", include_in_schema=False) async def get_open_api_endpoint(): openapi_schema = get_openapi( title=settings.PROJECT_NAME, version=settings.PROJECT_VERSION, description=settings.PROJECT_DESCRIPTION, routes=app.routes, ) # Ensure the OpenAPI version is set if "openapi" not in openapi_schema: openapi_schema["openapi"] = "3.0.2" return openapi_schema if __name__ == "__main__": uvicorn.run( app=app, host=settings.HOST, port=settings.PORT, reload=settings.DEBUG, log_level="info" )