Skip to content

Instantly share code, notes, and snippets.

@Montgoner
Created February 19, 2021 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Montgoner/0ab88f8b4a6515c654905aec5b069309 to your computer and use it in GitHub Desktop.
Save Montgoner/0ab88f8b4a6515c654905aec5b069309 to your computer and use it in GitHub Desktop.
def version_app(
app: FastAPI,
default_api_version: APIVersion,
exception_handlers: Optional[Dict[Union[int, Type[Exception]], Callable]],
**kwargs
):
app = VersionedFastAPI(
app,
version=default_api_version.to_str(), # Version that appears at the top of the API docs
default_version=default_api_version.to_tuple(), # Version at which unversioned endpoints start to be available
exception_handlers=exception_handlers,
**kwargs
)
# Hack: Register exception handlers in all mounted subapps
# We need this workaround because fastapi-versioning is not passing them downstream to sub-apps by default
mounted_routes = [route for route in app.routes if isinstance(route, Mount)]
if exception_handlers is not None:
for mounted_route in mounted_routes:
for exc, exc_handler in exception_handlers.items():
mounted_route.app.add_exception_handler(exc, exc_handler)
return app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment