This is the root object of the OpenAPI document. @param info: OpenAPIInfo Provides metadata about the API. @param openapi_spec: dict The content of openapi.json as a dict
| 202 | |
| 203 | @dataclass |
| 204 | class OpenAPI: |
| 205 | """ |
| 206 | This is the root object of the OpenAPI document. |
| 207 | |
| 208 | @param info: OpenAPIInfo Provides metadata about the API. |
| 209 | @param openapi_spec: dict The content of openapi.json as a dict |
| 210 | """ |
| 211 | |
| 212 | info: OpenAPIInfo = field(default_factory=OpenAPIInfo) |
| 213 | openapi_spec: dict = field(init=False) |
| 214 | openapi_file_override: bool = False # denotes whether there is an override or not. |
| 215 | |
| 216 | def __post_init__(self): |
| 217 | """ |
| 218 | Initializes the openapi_spec dict |
| 219 | """ |
| 220 | if self.openapi_file_override: |
| 221 | return |
| 222 | |
| 223 | self.openapi_spec = { |
| 224 | "openapi": "3.1.0", |
| 225 | "info": asdict(self.info), |
| 226 | "paths": {}, |
| 227 | "components": asdict(self.info.components), |
| 228 | "servers": [asdict(server) for server in self.info.servers], |
| 229 | "externalDocs": asdict(self.info.externalDocs) if self.info.externalDocs.url else None, |
| 230 | } |
| 231 | |
| 232 | def add_security_scheme(self, name: str, scheme: dict) -> None: |
| 233 | """Register a reusable security scheme (e.g. Bearer/API-key auth). |
| 234 | |
| 235 | Populating ``components.securitySchemes`` is what makes Swagger UI's |
| 236 | "Authorize" button appear and work; without it the button is either |
| 237 | absent or opens an empty popup (see #1122, #1339). |
| 238 | |
| 239 | @param name: str the key under ``components.securitySchemes`` (e.g. ``"BearerAuth"``). |
| 240 | @param scheme: dict the OpenAPI Security Scheme Object, e.g. |
| 241 | ``{"type": "http", "scheme": "bearer", "bearerFormat": "JWT"}``. |
| 242 | """ |
| 243 | if self.openapi_file_override: |
| 244 | return |
| 245 | self.openapi_spec["components"].setdefault("securitySchemes", {})[name] = scheme |
| 246 | |
| 247 | @property |
| 248 | def _security_scheme_names(self) -> list[str]: |
| 249 | return list(self.openapi_spec.get("components", {}).get("securitySchemes", {}) or {}) |
| 250 | |
| 251 | def prune_empty_components(self) -> None: |
| 252 | """Drop empty ``components`` buckets so the generated spec stays clean. |
| 253 | |
| 254 | In particular an empty ``securitySchemes: {}`` makes Swagger UI render an |
| 255 | empty "Available authorizations" popup; omitting it removes the button |
| 256 | entirely until the user actually configures a scheme (#1122, #1339). |
| 257 | """ |
| 258 | if self.openapi_file_override: |
| 259 | return |
| 260 | components = self.openapi_spec.get("components") |
| 261 | if isinstance(components, dict): |
no outgoing calls