Skip to content

Commit

Permalink
Allow adding routers by module path string
Browse files Browse the repository at this point in the history
  • Loading branch information
vitalik committed Sep 8, 2023
1 parent 72468a2 commit 14488b0
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 11 deletions.
10 changes: 4 additions & 6 deletions docs/docs/guides/routers.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,17 +109,15 @@ api = NinjaAPI()

Now we import all the routers from the various apps, and include them into the main API instance:

```Python hl_lines="2 3 4 8 9 10"
```Python hl_lines="2 6 7 8"
from ninja import NinjaAPI
from events.api import router as events_router
from news.api import router as news_router
from blogs.api import router as blogs_router

api = NinjaAPI()

api.add_router("/events/", events_router)
api.add_router("/news/", news_router)
api.add_router("/blogs/", blogs_router)
api.add_router("/events/", events_router) # You can add router object
api.add_router("/news/", "news.api.router") # or well add router by python path
api.add_router("/blogs/", "blogs.api.router")
```

Now, include `api` to your urls as usual and open your browser at `/api/docs`, and you should see all your routers combined into a single API:
Expand Down
7 changes: 6 additions & 1 deletion ninja/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from django.http import HttpRequest, HttpResponse
from django.urls import URLPattern, URLResolver, reverse
from django.utils.module_loading import import_string

from ninja.constants import NOT_SET, NOT_SET_TYPE
from ninja.errors import ConfigError, set_default_exc_handlers
Expand Down Expand Up @@ -359,12 +360,16 @@ def api_operation(
def add_router(
self,
prefix: str,
router: Router,
router: Union[Router, str],
*,
auth: Any = NOT_SET,
tags: Optional[List[str]] = None,
parent_router: Router = None,
) -> None:
if isinstance(router, str):
router = import_string(router)
assert isinstance(router, Router)

if auth is not NOT_SET:
router.auth = auth
if tags is not None:
Expand Down
6 changes: 2 additions & 4 deletions tests/demo_project/demo/urls.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from django.contrib import admin
from django.urls import path
from multi_param.api import router as multi_param
from someapp.api import router

from ninja import NinjaAPI

api_v1 = NinjaAPI()
api_v1.add_router("events", router)
api_v1.add_router("events", "someapp.api.router")
# TODO: check ^ for possible mistakes like `/events` `events/``


Expand Down Expand Up @@ -42,7 +40,7 @@ def put_foobar(request):


api_multi_param = NinjaAPI(version="1.0.1")
api_multi_param.add_router("", multi_param)
api_multi_param.add_router("", "multi_param.api.router")

urlpatterns = [
path("admin/", admin.site.urls),
Expand Down

0 comments on commit 14488b0

Please sign in to comment.