Django

Chapter 14-1 drf-yasg 사용법 완전 정리

Chansman 2025. 5. 21. 17:55

📘 drf-yasg 사용법 완전 정리

drf-yasg는 Django REST Framework에서 Swagger/OpenAPI 기반의 API 문서를 자동으로 생성해주는 강력한 도구입니다. 개발자와 클라이언트가 API를 더 쉽게 이해하고 테스트할 수 있도록 인터랙티브한 UI를 제공합니다.


✅ 1. 주요 기능 정리

  • 🔄 자동 문서 생성: APIView 또는 ViewSet 코드로부터 자동으로 문서 생성
  • 🧪 실시간 테스트 지원: Swagger UI 및 Redoc UI로 API 직접 테스트
  • 🔄 버전 관리 가능: API 버전별로 문서를 관리
  • 🛠 사용자 정의 문서화: 커스터마이징된 설명, 파라미터, 응답 등 세부 조정 가능

🛠️ 2. 설치 및 설정 방법

📦 설치 명령어

pip install drf-yasg

🧩 기본 설정 (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="My API",
      default_version='v1',
      description="My API description",
      terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="contact@myapi.local"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
   path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
   path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]

🔗 /swagger/: Swagger UI
🔗 /redoc/: Redoc UI


📋 3. 주요 기능 상세 사용법

🔹 API 정보 커스터마이징

openapi.Info(
   title="Custom API",
   default_version='v1',
   description="API 설명",
   terms_of_service="https://example.com",
   contact=openapi.Contact(email="example@example.com"),
   license=openapi.License(name="Apache 2.0"),
)

🔹 swagger_auto_schema 사용

from drf_yasg.utils import swagger_auto_schema
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import MySerializer

class MyAPIView(APIView):

    @swagger_auto_schema(
        operation_description="Retrieve a list of items",
        responses={200: MySerializer(many=True)},
    )
    def get(self, request):
        data = [{"id": 1, "name": "Item 1"}]
        return Response(data)

🔹 커스텀 스키마 정의

@swagger_auto_schema(
    operation_description="Retrieve a single item",
    responses={
        200: openapi.Response(
            description="A single item",
            schema=openapi.Schema(
                type=openapi.TYPE_OBJECT,
                properties={
                    'id': openapi.Schema(type=openapi.TYPE_INTEGER),
                    'name': openapi.Schema(type=openapi.TYPE_STRING),
                },
            ),
        ),
    }
)

🔹 파일 업로드 문서화

@swagger_auto_schema(
    manual_parameters=[
        openapi.Parameter(
            'file', openapi.IN_FORM,
            description="Upload a file",
            type=openapi.TYPE_FILE, required=True
        ),
    ],
    responses={200: 'File uploaded successfully'}
)

🔹 쿼리 파라미터 문서화

@swagger_auto_schema(
    manual_parameters=[
        openapi.Parameter(
            'search', openapi.IN_QUERY,
            description="Search items",
            type=openapi.TYPE_STRING
        )
    ]
)

🔒 4. 고급 설정: 인증 및 프로덕션 활용

🔐 인증 정보 포함

schema_view = get_schema_view(
    openapi.Info(title="My API", default_version='v1'),
    public=True,
    permission_classes=(permissions.AllowAny,),
    authentication_classes=[...],  # 예: JWTAuthentication
)

🧊 프로덕션에서 조건부 적용

if settings.DEBUG:
    urlpatterns += [
        path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    ]

🔗 5. 참고 링크


✅ drf-yasg는 실무에서도 API 테스트 및 문서 자동화를 위한 필수 도구입니다. Swagger와 Redoc의 UI를 자유롭게 선택하고, 필요한 인증 및 파라미터 설정을 통해 깔끔하고 명확한 API 문서를 구성해보세요!