Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 503
Pierre-Jean Coudert Avatar asked Jul 05 '13 20:07

Pierre-Jean Coudert


People also ask

What is Basename in router Django?

basename - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set basename when registering the viewset.

What is Default_authentication_classes?

DEFAULT_AUTHENTICATION_CLASSES. A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the request.

Where are routes defined in Django?

The routes are defined in the url.py file that can be either at the project or application level. We will focus on creating our route at the project level. To create a route in Django, we will use the path() function that accepts two parameters: a URL and a View function.


2 Answers

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

like image 97
paulhauner Avatar answered Oct 14 '22 15:10

paulhauner


If anyone wants an inline style

   router = DefaultRouter()     router.get_api_root_view().cls.__name__ = "Root API name"    router.get_api_root_view().cls.__doc__ = "Your Description" 
like image 41
digitake Avatar answered Oct 14 '22 14:10

digitake