Skip to content

Versioning

Different API version numbers

With Django Ninja Extra, it's very much easy to run multiple API versions from a single Django project.

All you have to do is create two or more NinjaAPI instances with different version arguments:

api_v1.py:

from ninja_extra import NinjaExtraAPI, route, api_controller

@api_controller
class MyV1Controller:
    @route.get('/hello')
    def hello(self):
        return {'message': 'Hello from V1'}

    @route.get('/example')
    def example(self):
        return {'message': 'Hello from V1 Example'}


api = NinjaExtraAPI(version='1.0.0')
api.register_controllers(MyV1Controller)

api_v2.py: You can reuse your APIControllers and make modifications to specific routes.

from ninja_extra import NinjaExtraAPI, route, api_controller
from .api_v1 import MyV1Controller

@api_controller
class MyV2Controller(MyV1Controller):
    @route.get('/example')
    def example(self):
        return {'message': 'Hello from V2 Example'}


api = NinjaExtraAPI(version='2.0.0')
api.register_controllers(MyV2Controller)

and then in urls.py:

...
from api_v1 import api as api_v1
from api_v2 import api as api_v2


urlpatterns = [
    ...
    path('api/v1/', api_v1.urls),
    path('api/v2/', api_v2.urls),
]

Now you can go to different OpenAPI docs pages for each version:

  • http://127.0.0.1/api/v1/docs
  • http://127.0.0.1/api/v2/docs

Different business logic

In the same way, you can define a different API for different components or areas:

...


api = NinjaExtraAPI(auth=token_auth, urls_namespace='public_api')
...

api_private = NinjaExtraAPI(auth=session_auth, urls_namespace='private_api')
...


urlpatterns = [
    ...
    path('api/', api.urls),
    path('internal-api/', api_private.urls),
]

Note

If you use different NinjaExtraAPI instances, you need to define different versions or different urls_namespaces. This is the same with NinjaAPI instances