django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

[BUG] Nested routers - Tags declared on parent routers are not added to operations

Open sumebrius opened this issue 1 year ago • 1 comments

When using nested routers, any tags added to a router that isn't the immediate parent of an operation are not added to the operation.

With the example below, the operation will have "Child Tag" added, but not "Parent Tag"

from ninja import NinjaAPI, Router

api = NinjaAPI()

parent_router = Router()
child_router = Router()

@child_router.get("/")
def hello(request):
    return "Hello World"

parent_router.add_router("child", child_router, tags=["Child Tag"])
api.add_router("/", parent_router, tags=["Parent Tag"])

Versions (please complete the following information):

  • Python version: 3.9
  • Django version: 4.1
  • Django-Ninja version: 0.22.2
  • Pydantic version: 1.10

sumebrius avatar Jul 17 '23 00:07 sumebrius

Ran into this issue myself recently. I think the fix for this specific issue may simply be an minor change to the Router.build_routers method.

https://github.com/steve148/django-ninja/tree/fix/nested-router-inherits-tags

Here's what I get from this change with the following API.

from ninja import NinjaAPI, Router


api = NinjaAPI(title="LFG API", version="1.0.0")

child_router = Router()


@child_router.get("/hello")
def hello(request):
    return {"message": "Hello from child router!"}


parent_router = Router()
parent_router.add_router("/child/", child_router, tags=["parent_to_child"])

api.add_router("/parent/", parent_router, tags=["api_to_parent"])
Screenshot 2024-03-16 at 8 06 09 PM

I did run into a bunch of other weird stuff while looking at tags and how they get inherited.

  1. If I set tags on the child_router = Router() definition, they don't show up in the OpenAPI schema.
  2. If I set tags on the @child_router.get("/hello") decorator, other tags are not included in the OpenAPI schema.

I would generally expect the tags list for an endpoint to always be extended when set by any level. This is also what it seems to be for FastAPI, which is my closest point of comparison here.

steve148 avatar Mar 17 '24 00:03 steve148