Search code examples
pythondjango-rest-frameworkopenapidrf-yasg

Django, drf-yasg - how to add description to tags?


Swagger documentation says you can do that:

https://swagger.io/docs/specification/grouping-operations-with-tags/

But unfortunately drf-yasg not implementing this feature:

https://github.com/axnsan12/drf-yasg/issues/454

It is said, that I can add custom generator class, but it is a very general answer. Now I see that drf_yasg.openapi.Swagger gets info block and I have thoughts, that this might be right place to put global tags section as an additional init argument, but it deeper, than customizing generator class and I have lack of knowledge of this module

Does anybody have solution to this particular problem, or at least maybe a link to some sort of tutorial, how to properly customize generator class?


Solution

  • Unfortunately, this is a current issue with drf-yasg.

    To actually achieve this, you need to create your own schema generator class:

    from drf_yasg.generators import OpenAPISchemaGenerator
    
    class CustomOpenAPISchemaGenerator(OpenAPISchemaGenerator):
      def get_schema(self, request=None, public=False):
        """Generate a :class:`.Swagger` object with custom tags"""
    
        swagger = super().get_schema(request, public)
        swagger.tags = [
            {
                "name": "api",
                "description": "everything about your API"
            },
            {
                "name": "users",
                "description": "everything about your users"
            },
        ]
    
        return swagger
    

    Make sure to also include it in your Schema View

    from drf_yasg.views import get_schema_view
    from drf_yasg import openapi
    
    schema_view = get_schema_view(
      openapi.Info(
        title="My API",
        default_version='v1',
      ),
      generator_class=CustomOpenAPISchemaGenerator,
    )
    

    Hope this works for you!