Skip to content

It should be possible to create two APIs with same urls_namespace #1615

@anentropic

Description

@anentropic

Django url namespaces are hierarchical rather than a flat global namespace.

Currently there is some validation to prevent creating two Ninja APIs with the same urls_namespace:

  File "/home/circleci/project/.venv/lib/python3.11/site-packages/ninja/main.py", line 436, in urls
    self._validate()
  File "/home/circleci/project/.venv/lib/python3.11/site-packages/ninja/main.py", line 577, in _validate
    raise ConfigError(msg.strip())
ninja.errors.ConfigError: Looks like you created multiple NinjaAPIs or TestClients
To let ninja distinguish them you need to set either unique version or urls_namespace
 - NinjaAPI(..., version='2.0.0')
 - NinjaAPI(..., urls_namespace='otherapi')
Already registered: ['reports']

But this seems like a mis-feature, because these APIs may be loaded into Django urlconf under different parent namespaces.

Relates to #1593

django-ninja/ninja/main.py

Lines 562 to 578 in e5806ca

def _validate(self) -> None:
# urls namespacing validation
skip_registry = os.environ.get("NINJA_SKIP_REGISTRY", False)
if (
not skip_registry
and self.urls_namespace in NinjaAPI._registry
and not debug_server_url_reimport()
):
msg = f"""
Looks like you created multiple NinjaAPIs or TestClients
To let ninja distinguish them you need to set either unique version or urls_namespace
- NinjaAPI(..., version='2.0.0')
- NinjaAPI(..., urls_namespace='otherapi')
Already registered: {NinjaAPI._registry}
"""
raise ConfigError(msg.strip())
NinjaAPI._registry.append(self.urls_namespace)

django-ninja/ninja/main.py

Lines 428 to 442 in e5806ca

def urls(self) -> Tuple[List[Union[URLResolver, URLPattern]], str, str]:
"""
str: URL configuration
Returns:
Django URL configuration
"""
self._validate()
return (
self._get_urls(),
"ninja",
self.urls_namespace.split(":")[-1],
# ^ if api included into nested urls, we only care about last bit here
)

The registry itself doesn't seem to serve any other purpose except prevent people from creating APIs with same namespace (?) ... but I don't think this should be disallowed in the first place?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions