33# setup logging, before importing anything else (and before creating other loggers)
44setup_logging ()
55
6- import json
76import logging
87
9- from fastapi import FastAPI , Request , Response # noqa: E402
8+ from fastapi import FastAPI , Request # noqa: E402
109from fastapi .middleware .cors import CORSMiddleware # noqa: E402
1110from fastapi .responses import JSONResponse # noqa: E402
1211from fastapi .routing import APIRoute # noqa: E402
12+ from fastapi .openapi .utils import get_openapi
1313
1414from src .core .config import get_settings # noqa: E402
1515from src .middleware import AuditMiddleware # noqa: E402
16+ from src .middleware .request_context import RequestContextMiddleware # noqa: E402
1617from src .routers .main import api_router # noqa: E402
1718from src .utils .openapi_converter import convert_openapi_spec # noqa: E402
1819
@@ -35,6 +36,38 @@ def custom_generate_unique_id(route: APIRoute) -> str:
3536 generate_unique_id_function = custom_generate_unique_id ,
3637)
3738
39+ def custom_openapi ():
40+ if app .openapi_schema :
41+ return app .openapi_schema
42+
43+ openapi_schema = get_openapi (
44+ title = app .title ,
45+ version = "1.0.0" ,
46+ description = app .description ,
47+ routes = app .routes ,
48+ )
49+
50+ # Add security scheme for Bearer token
51+ openapi_schema ["components" ]["securitySchemes" ] = {
52+ "BearerAuth" : {
53+ "type" : "http" ,
54+ "scheme" : "bearer" ,
55+ "bearerFormat" : "JWT" ,
56+ "description" : "Enter your bearer token for Azure AD authentication"
57+ }
58+ }
59+
60+ # Apply security globally to all endpoints
61+ for path in openapi_schema ["paths" ]:
62+ for method in openapi_schema ["paths" ][path ]:
63+ if method != "parameters" :
64+ openapi_schema ["paths" ][path ][method ]["security" ] = [{"BearerAuth" : []}]
65+
66+ app .openapi_schema = openapi_schema
67+ return app .openapi_schema
68+
69+ app .openapi = custom_openapi
70+
3871app .add_middleware (
3972 CORSMiddleware ,
4073 allow_origins = ["*" ],
@@ -43,6 +76,7 @@ def custom_generate_unique_id(route: APIRoute) -> str:
4376 allow_headers = ["*" ],
4477)
4578
79+ app .add_middleware (RequestContextMiddleware )
4680app .add_middleware (AuditMiddleware )
4781app .include_router (api_router , prefix = config .API_PREFIX )
4882
0 commit comments