2# +==== BEGIN CatFeeder =================+
5# ...............)..(.')
7# ...............\(__)|
8# Inspired by Joan Stark
9# source https://www.asciiart.eu/
13# FILE: swagger_class.py
14# CREATION DATE: 26-11-2025
15# LAST Modified: 22:34:3 11-01-2026
17# This is the backend server in charge of making the actual website work.
19# COPYRIGHT: (c) Cat Feeder
20# PURPOSE: The class in charge of handling the swagger instance.
22# +==== END CatFeeder =================+
24from typing
import Optional, Dict, Any, TYPE_CHECKING
25from fastapi
import FastAPI, Request, Response
26from fastapi.openapi.docs
import get_swagger_ui_html, get_redoc_html
27from fastapi.openapi.utils
import get_openapi
28from display_tty
import Disp, initialise_logger
29from .
import swagger_constants
as SWAGGER_CONST
30from ...core
import FinalClass, RuntimeControl, RuntimeManager, RI
31from ...http_codes
import HCI, HTTP_DEFAULT_TYPE
32from ...server_header
import ServerHeaders
33from ...boilerplates
import BoilerplateResponses, BoilerplateIncoming
36 from ...path_manager
import PathManager
40 """Handler for Swagger/OpenAPI documentation integration.
42 This class manages the configuration and injection of Swagger UI
43 documentation interface into the FastAPI application. It provides endpoints
44 for accessing interactive API documentation and the OpenAPI schema.
47 disp (Disp): Logger instance for this class.
48 debug (bool): Debug mode flag.
49 success (int): Success return code.
50 error (int): Error return code.
51 runtime_manager (RuntimeManager): Shared runtime manager instance.
52 path_manager_initialised (PathManager): Path manager for registering endpoints.
53 runtime_control_initialised (RuntimeControl): Runtime control for accessing app instance.
54 server_headers_initialised (ServerHeaders): Server header configuration.
55 boilerplate_responses_initialised (BoilerplateResponses): Response templates.
56 boilerplate_incoming_initialised (BoilerplateIncoming): Request handling utilities.
59 disp: Disp = initialise_logger(__qualname__,
False)
61 def __init__(self, success: int = 0, error: int = 84, debug: bool =
False) ->
None:
62 """Initialize the SwaggerHandler.
65 success (int, optional): Success return code. Defaults to 0.
66 error (int, optional): Error return code. Defaults to 84.
67 debug (bool, optional): Enable debug logging. Defaults to False.
70 self.
disp.update_disp_debug(debug)
71 self.
disp.log_debug(
"Initialising...")
88 self.
disp.log_debug(
"Initialised")
91 """Generate custom OpenAPI schema with metadata.
94 app (FastAPI): The FastAPI application instance.
97 Dict[str, Any]: The OpenAPI schema dictionary.
99 func_title =
"_get_custom_openapi_schema"
100 self.
disp.log_debug(
"Generating custom OpenAPI schema", func_title)
102 if app.openapi_schema:
103 self.
disp.log_debug(
"Returning cached OpenAPI schema", func_title)
104 return app.openapi_schema
106 openapi_schema = get_openapi(
107 title=SWAGGER_CONST.API_TITLE,
108 version=SWAGGER_CONST.API_VERSION,
109 description=SWAGGER_CONST.API_DESCRIPTION,
111 tags=SWAGGER_CONST.TAGS_METADATA,
112 servers=SWAGGER_CONST.SERVERS,
115 openapi_schema[
"info"][
"contact"] = SWAGGER_CONST.CONTACT_INFO
116 openapi_schema[
"info"][
"license"] = SWAGGER_CONST.LICENSE_INFO
118 app.openapi_schema = openapi_schema
119 self.
disp.log_debug(
"OpenAPI schema generated and cached", func_title)
120 return app.openapi_schema
123 """Wrapper method for app.openapi() that uses the custom schema generator.
125 This method serves as the openapi() callable for the FastAPI app instance.
128 app (FastAPI): The FastAPI application instance.
131 Dict[str, Any]: The OpenAPI schema dictionary.
136 """Endpoint to serve Swagger UI documentation.
139 request (Request): The incoming request object.
142 Response: HTML response with Swagger UI interface.
144 func_title =
"get_swagger_documentation"
145 self.
disp.log_debug(
"Serving Swagger UI", func_title)
149 self.
disp.log_debug(f
"token = {token}", func_title)
154 message=
"Application not initialized",
155 resp=
"App instance not found",
159 return HCI.service_unavailable(
161 content_type=HTTP_DEFAULT_TYPE,
165 return get_swagger_ui_html(
166 openapi_url=SWAGGER_CONST.OPENAPI_URL,
167 title=f
"{SWAGGER_CONST.API_TITLE} - Swagger UI",
168 oauth2_redirect_url=SWAGGER_CONST.SWAGGER_REDIRECT_URL,
169 swagger_ui_parameters=SWAGGER_CONST.SWAGGER_UI_PARAMETERS,
173 """Endpoint to serve ReDoc documentation.
176 request (Request): The incoming request object.
179 Response: HTML response with ReDoc interface.
181 func_title =
"get_redoc_documentation"
182 self.
disp.log_debug(
"Serving ReDoc", func_title)
186 self.
disp.log_debug(f
"token = {token}", func_title)
191 message=
"Application not initialized",
192 resp=
"App instance not found",
196 return HCI.service_unavailable(
198 content_type=HTTP_DEFAULT_TYPE,
202 return get_redoc_html(
203 openapi_url=SWAGGER_CONST.OPENAPI_URL,
204 title=f
"{SWAGGER_CONST.API_TITLE} - ReDoc",
208 """Endpoint to serve the OpenAPI JSON schema.
211 request (Request): The incoming request object.
214 Response: JSON response with OpenAPI schema.
216 func_title =
"get_openapi_schema"
217 self.
disp.log_debug(
"Serving OpenAPI schema", func_title)
221 self.
disp.log_debug(f
"token = {token}", func_title)
225 title=
"OpenAPI Schema",
226 message=
"Application not initialized",
227 resp=
"App instance not found",
231 return HCI.service_unavailable(
233 content_type=HTTP_DEFAULT_TYPE,
242 content=openapi_schema,
243 content_type=HTTP_DEFAULT_TYPE,
247 def inject(self, app: Optional[
"FastAPI"] =
None) -> int:
248 """Inject Swagger/OpenAPI configuration into the FastAPI application.
250 This method configures the FastAPI application with custom OpenAPI documentation
251 settings and registers the documentation endpoints (Swagger UI, OpenAPI schema).
254 app (Optional[FastAPI], optional): The FastAPI application instance.
255 If None, uses the instance from RuntimeControl. Defaults to None.
258 int: success if injection succeeded, error if there was an error.
261 RuntimeError: If no FastAPI application instance is available.
263 func_title =
"inject"
264 self.
disp.log_debug(
"Starting Swagger injection", func_title)
271 "No FastAPI app instance available", func_title)
272 raise RuntimeError(
"FastAPI application instance not found")
274 if not isinstance(app, FastAPI):
276 f
"Invalid app type: {type(app)}, expected FastAPI",
281 self.
disp.log_debug(
"Configuring FastAPI OpenAPI settings", func_title)
285 app.openapi_url =
None
287 app.title = SWAGGER_CONST.API_TITLE
288 app.version = SWAGGER_CONST.API_VERSION
289 app.description = SWAGGER_CONST.API_DESCRIPTION
290 app.openapi_tags = SWAGGER_CONST.TAGS_METADATA
291 app.contact = SWAGGER_CONST.CONTACT_INFO
292 app.license_info = SWAGGER_CONST.LICENSE_INFO
293 app.servers = SWAGGER_CONST.SERVERS
295 self.
disp.log_debug(
"Registering documentation endpoints", func_title)
298 path=SWAGGER_CONST.SWAGGER_URL,
304 f
"Failed to register Swagger UI endpoint at {SWAGGER_CONST.SWAGGER_URL}",
309 def custom_openapi() -> Dict[str, Any]:
312 app.openapi = custom_openapi
315 "Swagger/OpenAPI injection completed successfully", func_title)
317 f
"Swagger UI available at: {SWAGGER_CONST.SWAGGER_URL}", func_title)
319 f
"OpenAPI schema available at: {SWAGGER_CONST.OPENAPI_URL}", func_title)
RuntimeManager path_manager_initialised
Response get_swagger_documentation(self, Request request)
RuntimeControl runtime_control_initialised
BoilerplateResponses boilerplate_responses_initialised
Response get_openapi_schema(self, Request request)
Dict[str, Any] _custom_openapi_wrapper(self, "FastAPI" app)
int inject(self, Optional["FastAPI"] app=None)
Response get_redoc_documentation(self, Request request)
RuntimeManager runtime_manager
None __init__(self, int success=0, int error=84, bool debug=False)
ServerHeaders server_headers_initialised
Dict[str, Any] _get_custom_openapi_schema(self, "FastAPI" app)
BoilerplateIncoming boilerplate_incoming_initialised