2# +==== BEGIN CatFeeder =================+
5# ...............)..(.')
7# ...............\(__)|
8# Inspired by Joan Stark
9# source https://www.asciiart.eu/
14# CREATION DATE: 26-11-2025
15# LAST Modified: 22:22:17 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 redoc instance.
22# +==== END CatFeeder =================+
24from typing
import Optional, Dict, Any, TYPE_CHECKING
25from fastapi
import FastAPI, Request, Response
26from fastapi.openapi.docs
import get_redoc_html
27from fastapi.openapi.utils
import get_openapi
28from display_tty
import Disp, initialise_logger
29from .
import redoc_constants
as REDOC_CONST
30from ...core
import FinalClass, RuntimeControl
31from ...http_codes
import HCI, HTTP_DEFAULT_TYPE
32from ...core.runtime_manager
import RuntimeManager, RI
33from ...server_header
import ServerHeaders
34from ...path_manager
import PathManager
35from ...boilerplates
import BoilerplateResponses, BoilerplateIncoming
38 from fastapi
import Request, Response
42 """Handler for Swagger/OpenAPI documentation integration.
44 This class manages the configuration and injection of Swagger UI and ReDoc
45 documentation interfaces into the FastAPI application. It provides endpoints
46 for accessing interactive API documentation and the OpenAPI schema.
49 disp (Disp): Logger instance for this class.
50 debug (bool): Debug mode flag.
51 success (int): Success return code.
52 error (int): Error return code.
53 runtime_manager (RuntimeManager): Shared runtime manager instance.
54 path_manager_initialised (PathManager): Path manager for registering endpoints.
55 runtime_control_initialised (RuntimeControl): Runtime control for accessing app instance.
56 server_headers_initialised (ServerHeaders): Server header configuration.
57 boilerplate_responses_initialised (BoilerplateResponses): Response templates.
58 boilerplate_incoming_initialised (BoilerplateIncoming): Request handling utilities.
61 disp: Disp = initialise_logger(__qualname__,
False)
63 def __init__(self, success: int = 0, error: int = 84, debug: bool =
False) ->
None:
64 """Initialize the SwaggerHandler.
67 success (int, optional): Success return code. Defaults to 0.
68 error (int, optional): Error return code. Defaults to 84.
69 debug (bool, optional): Enable debug logging. Defaults to False.
72 self.
disp.update_disp_debug(debug)
73 self.
disp.log_debug(
"Initialising...")
93 self.
disp.log_debug(
"Initialised")
96 """Generate custom OpenAPI schema with metadata.
99 app (FastAPI): The FastAPI application instance.
102 Dict[str, Any]: The OpenAPI schema dictionary.
104 func_title =
"_get_custom_openapi_schema"
105 self.
disp.log_debug(
"Generating custom OpenAPI schema", func_title)
107 if app.openapi_schema:
108 self.
disp.log_debug(
"Returning cached OpenAPI schema", func_title)
109 return app.openapi_schema
111 openapi_schema = get_openapi(
112 title=REDOC_CONST.API_TITLE,
113 version=REDOC_CONST.API_VERSION,
114 description=REDOC_CONST.API_DESCRIPTION,
116 tags=REDOC_CONST.TAGS_METADATA,
117 servers=REDOC_CONST.SERVERS,
120 openapi_schema[
"info"][
"contact"] = REDOC_CONST.CONTACT_INFO
121 openapi_schema[
"info"][
"license"] = REDOC_CONST.LICENSE_INFO
123 app.openapi_schema = openapi_schema
124 self.
disp.log_debug(
"OpenAPI schema generated and cached", func_title)
125 return app.openapi_schema
128 """Wrapper method for app.openapi() that uses the custom schema generator.
130 This method serves as the openapi() callable for the FastAPI app instance.
133 app (FastAPI): The FastAPI application instance.
136 Dict[str, Any]: The OpenAPI schema dictionary.
141 """Endpoint to serve ReDoc documentation.
144 request (Request): The incoming request object.
147 Response: HTML response with ReDoc interface.
149 func_title =
"get_redoc_documentation"
150 self.
disp.log_debug(
"Serving ReDoc", func_title)
154 self.
disp.log_debug(f
"token = {token}", func_title)
159 message=
"Application not initialized",
160 resp=
"App instance not found",
164 return HCI.service_unavailable(
166 content_type=HTTP_DEFAULT_TYPE,
170 return get_redoc_html(
171 openapi_url=REDOC_CONST.OPENAPI_URL,
172 title=f
"{REDOC_CONST.API_TITLE} - ReDoc",
176 """Endpoint to serve the OpenAPI JSON schema.
179 request (Request): The incoming request object.
182 Response: JSON response with OpenAPI schema.
184 func_title =
"get_openapi_schema"
185 self.
disp.log_debug(
"Serving OpenAPI schema", func_title)
189 self.
disp.log_debug(f
"token = {token}", func_title)
193 title=
"OpenAPI Schema",
194 message=
"Application not initialized",
195 resp=
"App instance not found",
199 return HCI.service_unavailable(
201 content_type=HTTP_DEFAULT_TYPE,
210 content=openapi_schema,
211 content_type=HTTP_DEFAULT_TYPE,
215 def inject(self, app: Optional[
"FastAPI"] =
None) -> int:
216 """Inject Swagger/OpenAPI configuration into the FastAPI application.
218 This method configures the FastAPI application with custom OpenAPI documentation
219 settings and registers the documentation endpoints (Swagger UI, ReDoc, OpenAPI schema).
222 app (Optional[FastAPI], optional): The FastAPI application instance.
223 If None, uses the instance from RuntimeControl. Defaults to None.
226 int: success if injection succeeded, error if there was an error.
229 RuntimeError: If no FastAPI application instance is available.
231 func_title =
"inject"
232 self.
disp.log_debug(
"Starting Swagger injection", func_title)
239 "No FastAPI app instance available", func_title)
240 raise RuntimeError(
"FastAPI application instance not found")
242 if not isinstance(app, FastAPI):
244 f
"Invalid app type: {type(app)}, expected FastAPI",
249 self.
disp.log_debug(
"Configuring FastAPI OpenAPI settings", func_title)
253 app.openapi_url =
None
255 app.title = REDOC_CONST.API_TITLE
256 app.version = REDOC_CONST.API_VERSION
257 app.description = REDOC_CONST.API_DESCRIPTION
258 app.openapi_tags = REDOC_CONST.TAGS_METADATA
259 app.contact = REDOC_CONST.CONTACT_INFO
260 app.license_info = REDOC_CONST.LICENSE_INFO
261 app.servers = REDOC_CONST.SERVERS
263 self.
disp.log_debug(
"Registering documentation endpoints", func_title)
266 path=REDOC_CONST.REDOC_URL,
272 f
"Failed to register ReDoc endpoint at {REDOC_CONST.REDOC_URL}",
277 def custom_openapi() -> Dict[str, Any]:
280 app.openapi = custom_openapi
283 "ReDoc/OpenAPI injection completed successfully", func_title)
285 f
"ReDoc available at: {REDOC_CONST.REDOC_URL}", func_title)
287 f
"OpenAPI schema available at: {REDOC_CONST.OPENAPI_URL}", func_title)
int inject(self, Optional["FastAPI"] app=None)
Response get_openapi_schema(self, Request request)
RuntimeManager runtime_manager
BoilerplateIncoming boilerplate_incoming_initialised
Dict[str, Any] _custom_openapi_wrapper(self, "FastAPI" app)
BoilerplateResponses boilerplate_responses_initialised
RuntimeControl runtime_control_initialised
None __init__(self, int success=0, int error=84, bool debug=False)
Dict[str, Any] _get_custom_openapi_schema(self, "FastAPI" app)
ServerHeaders server_headers_initialised
Response get_redoc_documentation(self, Request request)
PathManager path_manager_initialised