How to order endpoints Django rest swagger - a1k89/Blog GitHub Wiki

Prepare

  • Your have a Django with Django rest framework
  • You have a drf-yasg library
  • You have some endpoints

Problems

  • Unordered list of endpoints and upset frontend developers

Solution

urls.py

from drf_yasg.inspectors import SwaggerAutoSchema

class OrderedSwaggerAutoSchema(SwaggerAutoSchema):
   def get_tags(self, operation_keys=None):
      tags = self.overrides.get('tags', None) or getattr(self.view, 'tags', [])
      if not tags:
         tags = [operation_keys[0]]
      return tags

settings.py

SWAGGER_SETTINGS = {"DEFAULT_AUTO_SCHEMA_CLASS": "path.to.your.OrderedSwaggerAutoSchema"}

helper.py

import enum

class Tags(enum.Enum):
    TEST = 'Test endpoints'
    PSY = 'Actions for psy'
    QUESTIONS = 'Questions'
    DIALOGS = 'Dialoges'

And finally in your views:

class TestGenericApiView(generics.ListCreateAPIView):
    """
    List/create something
    """

    queryset = Test.objects.all()
    serializer_class = TestSerializer
    tags = [Tags.TEST.value] # here

Conclusion

  • Now we have groups of endpoints