Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I exclude a view from the API documentation?

I use django-rest-framework (DRF) to provide the REST API of a site of mine. From what I understand, the automatic generation of API documentation relies on DRF's generation of a schema. It may then be interpreted by a third-party tool to produce pretty documentation. I've used django-rest-swagger as the tool that produces the pretty documentation from DRF's schema, but I suspect the solution to my problem is DRF-based, independent of whatever tool I use to transform the schema to something "pretty".

The problem is that by default, DRF provides documentation for the whole API, even though some parts of it are really for my sites own internal purpose. I'd like some views to be excluded from the documentation. Some views should always be excluded. Some views should be excluded only if the user viewing the documentation is not logged into the site.

like image 678
Louis Avatar asked Jan 10 '17 11:01

Louis


1 Answers

This isn't well documented. On a class-based view, you can set the exclude_from_schema attribute to True to exclude the view from the documentation. Example:

from rest_framework import viewsets, mixins
class SomeViewSet(mixins...., viewsets.GenericViewSet):
    exclude_from_schema = True

    [...]

If you search the current documentation for exclude_from_schema you'll find a hit here, which documents the presence of a parameter for the @api_view decorator, which has for effect of setting the attribute as shown above. The attribute itself though is currently not mentioned in DRF's documentation.

If you want to exclude a view based on a condition, you can use the @property decorator so that exclude_from_schema becomes a computed attribute. Behind the scenes, when DRF needs to produce the schema for the view, it will instantiate the class with the Request object that was generated when the user browsed to the documentation page. So you can test to check whether the user that is accessing the documentation was authenticated or not:

from rest_framework import viewsets, mixins, permissions
class SomeViewSet(mixins...., viewsets.GenericViewSet):
    @property
    def exclude_from_schema(self):
        return not permissions.IsAuthenticated().has_permission(self.request,
                                                                self)

    [...]

self.request is the Request object that was generated when the user asked for the documentation. We use one of the classes provided by rest_framework.permissions directly because the code that generates the schema does not use the permission_classes attribute that may be set on SomeViewSet.

like image 141
Louis Avatar answered Oct 07 '22 21:10

Louis