Create a function that combines OpenAPI schemas from multiple FastAPI apps. Args: main_app: The main FastAPI application mounted_apps: Dictionary of mounted apps with their mount paths as keys title: Title for the combined OpenAPI schema version: Version str
(
main_app: FastAPI,
mounted_apps: Dict[str, FastAPI],
title: str = "Combined API",
version: str = "1.0.0",
description: str = "Combined API Schema",
)
| 10 | |
| 11 | |
| 12 | def create_combined_openapi_fn( |
| 13 | main_app: FastAPI, |
| 14 | mounted_apps: Dict[str, FastAPI], |
| 15 | title: str = "Combined API", |
| 16 | version: str = "1.0.0", |
| 17 | description: str = "Combined API Schema", |
| 18 | ): |
| 19 | """ |
| 20 | Create a function that combines OpenAPI schemas from multiple FastAPI apps. |
| 21 | |
| 22 | Args: |
| 23 | main_app: The main FastAPI application |
| 24 | mounted_apps: Dictionary of mounted apps with their mount paths as keys |
| 25 | title: Title for the combined OpenAPI schema |
| 26 | version: Version string for the combined schema |
| 27 | description: Description for the combined schema |
| 28 | |
| 29 | Returns: |
| 30 | A function that can be assigned to app.openapi |
| 31 | """ |
| 32 | |
| 33 | def custom_openapi(): |
| 34 | # Return cached schema if available |
| 35 | if main_app.openapi_schema: |
| 36 | return main_app.openapi_schema |
| 37 | |
| 38 | # Get the OpenAPI schema for the main app |
| 39 | openapi_schema = get_openapi( |
| 40 | title=title, |
| 41 | version=version, |
| 42 | description=description, |
| 43 | routes=main_app.routes, |
| 44 | ) |
| 45 | |
| 46 | # Add paths from mounted apps with proper prefixes |
| 47 | for mount_path, app in mounted_apps.items(): |
| 48 | # Skip apps mounted at root (these should be handled separately) |
| 49 | if mount_path == "/": |
| 50 | prefix = "" |
| 51 | else: |
| 52 | # Ensure mount_path starts with / and doesn't end with / |
| 53 | mount_path = "/" + mount_path.strip("/") |
| 54 | prefix = mount_path |
| 55 | |
| 56 | # Get schema for the mounted app |
| 57 | app_schema = get_openapi( |
| 58 | title=f"{app.title}" if hasattr(app, 'title') else "API", |
| 59 | version=version, |
| 60 | routes=app.routes, |
| 61 | ) |
| 62 | |
| 63 | # Add paths with appropriate prefix |
| 64 | for path, path_item in app_schema.get("paths", {}).items(): |
| 65 | # Handle root paths specially (e.g., "/" becomes "/api/") |
| 66 | if path == "/": |
| 67 | path = "" |
| 68 | # Add the path with the appropriate prefix |
| 69 | openapi_schema["paths"][f"{prefix}{path}"] = path_item |
no outgoing calls
no test coverage detected
searching dependent graphs…