DevOps/Django

[DRF] Swagger 사용하기

bestwish 2023. 1. 9. 00:18

https://drf-yasg.readthedocs.io/en/stable/readme.html

 

drf-yasg - Yet another Swagger generator — drf-yasg 1.20.1 documentation

Since the schema does not usually change during the lifetime of the django process, there is out of the box support for caching the schema view in-memory, with some sane defaults: caching is enabled by the cache_page decorator, using the default Django cac

drf-yasg.readthedocs.io

 

1. Swagger 설치

1. 설치

pip install drf-yasg

2. settings.py

INSTALLED_APPS = [
   ...
   'drf_yasg',
   ...
]

3. <project>/urls.py

...
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

...

schema_view = get_schema_view(
   openapi.Info(
      title="Snippets API",
      default_version='v1',
      description="Test description",
      terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="contact@snippets.local"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=[permissions.AllowAny],
)

urlpatterns = [
   re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
   re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
   re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
   ...
]

 

2. View에서 활용.

1. APIView

# views.py
from drf_yasg.utils import swagger_auto_schema

class PostListAPIView(APIView):
    def get(self, request, format=None):
        post = Post.objects.all()
        serializer = PostSerializer(post, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
	
    @swagger_auto_schema(request_body=PostSerializer) # 추가
    def post(self, request):
        serializer =  PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

APIView는 swagger_auto_schema를 추가해야 swagger에 명세가 추가된다.

2. Generics

# views.py
class PostListAPIView(ListCreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

Generics는 따로 설정하지 않아도 swagger에 잘 나타난다.

다만, ModelSerializer를 사용하지 않고 Serializer를 사용했을때는 model에 있는 필드들을 설정해줘야 swagger에 나타난다.