""" 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.Token.config import Auth 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 Auth": { "type": "apiKey", "in": "header", "name": Auth.ACCESS_TOKEN_TAG, "description": "Enter: **'Bearer <JWT>'**, where JWT is the access 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 """ from open_api_creator import create_openapi_schema # Get all routers and protected routes using the dynamic route creation app = FastAPI( title=Config.TITLE, description=Config.DESCRIPTION, default_response_class=JSONResponse, ) # Initialize FastAPI app @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) app.openapi = lambda app=app: create_openapi_schema(app) return app