diff --git a/ninja/router.py b/ninja/router.py index c1d1372a..13e26d41 100644 --- a/ninja/router.py +++ b/ninja/router.py @@ -12,6 +12,7 @@ from django.urls import URLPattern from django.urls import path as django_path +from django.utils.module_loading import import_string from ninja.constants import NOT_SET, NOT_SET_TYPE from ninja.errors import ConfigError @@ -371,12 +372,16 @@ def urls_paths(self, prefix: str) -> Iterator[URLPattern]: def add_router( self, prefix: str, - router: "Router", + router: Union["Router", str], *, auth: Any = NOT_SET, throttle: Union[BaseThrottle, List[BaseThrottle], NOT_SET_TYPE] = NOT_SET, tags: Optional[List[str]] = None, ) -> None: + if isinstance(router, str): + router = import_string(router) + assert isinstance(router, Router) + if self.api: # we are already attached to an api self.api.add_router( diff --git a/tests/test_router_add_router.py b/tests/test_router_add_router.py new file mode 100644 index 00000000..545c9e23 --- /dev/null +++ b/tests/test_router_add_router.py @@ -0,0 +1,22 @@ +from ninja import NinjaAPI, Router +from ninja.testing import TestClient + + +router = Router() + + +@router.get("/") +def op(request): + return True + + +def test_add_router_with_string_path(): + main_router = Router() + main_router.add_router("sub", "tests.test_router_add_router.router") + + api = NinjaAPI() + api.add_router("main", main_router) + + client = TestClient(api) + + assert client.get("/main/sub/").status_code == 200