Search code examples
djangodjango-rest-frameworkdocstring

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


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 ?


Solution

  • I'm new to this but I found you can use a SimpleRouter instead of a DefaultRouter to specify your own APIRoot.

    in urls.py in your api module

    from django.conf.urls import patterns, url, include
    from rest_framework.routers import SimpleRouter
    router = SimpleRouter()
    
    urlpatterns = patterns('api.views',
        url(r'^$', views.APIRoot.as_view()),
        url(r'', include(router.urls)),
    )
    

    Then specify the documentation in the class comment

    from rest_framework import generics
    
    class APIRoot(generics.GenericAPIView):
        """
        My API documentation
        """