In Django RestFramework, how to change the Api Root documentation?

Pierre-Jean Coudert picture Pierre-Jean Coudert · Jul 5, 2013 · Viewed 12.1k times · Source

In django RestFramework, is there any "official" way to generate the documentation for the "Api Root" ?

After looking at the RestFramework's source code, I've found a work around by subclassing the DefaultRouter:

from rest_framework import routers

class MyRouter(routers.DefaultRouter):
    def get_api_root_view(self):
        api_root_view = super(MyRouter, self).get_api_root_view()
        ApiRootClass = api_root_view.cls

        class MyAPIRoot(ApiRootClass):
            """My API Root documentation"""
            pass

        return MyAPIRoot.as_view()

router = MyRouter()

Is there a cleaner or better way ?

Answer

paulhauner picture paulhauner · May 30, 2017

I found a solution through experimentation.

I prefer it to the other solutions in this thread as it requires less code and allows you to customise the API title, as well as the documentation for the API root.

from rest_framework import routers

class ThisWillBeTheApiTitleView(routers.APIRootView):
    """
    This appears where the docstring goes!
    """
    pass


class DocumentedRouter(routers.DefaultRouter):
    APIRootView = ThisWillBeTheApiTitleView


router = DocumentedRouter()
router.register(r'items', ItemsViewSet)

This renders as below:

Demonstration