djangodjango-rest-frameworkopenapiredocdrf-spectacular

How to document individual actions of a ViewSet using `drf-spectacular`?


Using DRF's built-in way of documenting the API, I was able to write a docstring like the following and each action was documented by its corresponding line:

"""
list:    The list action returns all available objects.
retrieve:The retrieve action returns a single object selected by `id`.
create:  The create action expects the fields `name`, creates a new object and returns it.
"""

I am in the middle of switching to the library drf-spectacular, which allows for an easy generation of OpenAPI conforming schemes. However, the same docstring is now rendered for every action, which makes my documentation really long and redundant.

Is there a way that only the relevant part of the docstring is rendered for each action?


Solution

  • I have just found out that the library provides very in-depth documentation functionality via their decorators. Without overriding any of the ViewSet methods, the above docstring could be written as:

    @extend_schema_view(
        list=extend_schema(
            description="The list action returns all available actions."
        ),
        create=extend_schema(
            description="The create action expects the fields `name`, creates a new object and returns it."
        ),
        retrieve=extend_schema(
            description="The retrieve action returns a single object selected by `id`."
        )
    )
    class MyViewSet(viewsets.ViewSet):
        pass