""" FastAPI Application Factory Module This module provides functionality to create and configure a FastAPI application with: - Custom OpenAPI schema configuration - Security scheme configuration for Bearer authentication - Automatic router registration - Response class configuration - Security requirements for protected endpoints """ from typing import Any, Dict, List, Tuple from fastapi import FastAPI, APIRouter from fastapi.responses import JSONResponse, RedirectResponse from fastapi.openapi.utils import get_openapi from AllConfigs.main import MainConfig as Config from create_routes import get_all_routers def setup_security_schema() -> Dict[str, Any]: """ Configure security schema for the OpenAPI documentation. Returns: Dict[str, Any]: Security schema configuration """ return { "components": { "securitySchemes": { "Bearer": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT", "description": "Enter the token" } } } } def configure_route_security( path: str, method: str, schema: Dict[str, Any], protected_paths: List[str] ) -> None: """ Configure security requirements for a specific route. Args: path: Route path method: HTTP method schema: OpenAPI schema to modify protected_paths: List of paths that require authentication """ if path in protected_paths: if "paths" in schema and path in schema["paths"]: if method.lower() in schema["paths"][path]: schema["paths"][path][method.lower()]["security"] = [{"Bearer": []}] def create_app() -> FastAPI: """ Create and configure a FastAPI application with dynamic route creation. Returns: FastAPI: Configured FastAPI application instance """ # Initialize FastAPI app app = FastAPI( title=Config.TITLE, description=Config.DESCRIPTION, default_response_class=JSONResponse, ) @app.get("/", include_in_schema=False, summary=str(Config.DESCRIPTION)) async def home() -> RedirectResponse: """Redirect root path to API documentation.""" return RedirectResponse(url="/docs") # Get all routers and protected routes using the dynamic route creation routers, protected_routes = get_all_routers() # Include all routers for router in routers: app.include_router(router) # Configure OpenAPI schema with security def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="WAG Management API", version="4.0.0", description="WAG Management API Service", routes=app.routes, ) # Add security scheme security_schema = setup_security_schema() openapi_schema.update(security_schema) # Configure security for protected routes for path, methods in protected_routes.items(): for method in methods: configure_route_security(path, method, openapi_schema, list(protected_routes.keys())) app.openapi_schema = openapi_schema return app.openapi_schema app.openapi = custom_openapi return app