API 문서를 자동으로 생성하고, 클라이언트가 API 요청을 쉽게 테스트할 수 있도록 도와주는 도구
poetry add drf-yasg
, 패키지 리소스가 없다는 오류가 뜨면 poetry add setuptools
-> installed drf_yasg
,# config/schema.py 생성
from django.urls import re_path
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,],
)
from config.schema import schema_view
path('swagger<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'),
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'),
# user/views.py
class SignUpAPIView(CreateAPIView):
serializer_class = SignUpSerializer
@swagger_auto_schema(
request_body=SignUpSerializer,
responses={201: UsernameSerializer(many=False)}
)
def post(self, request, *args, **kwargs):
return super().post(request, *args, **kwargs)
# serializers.py
# 안쓸꺼지만 username만 나오게 하려고 만든 함수
class UsernameSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username']
drf-yasg
는 Django REST Framework(DRF)에서 Swagger/OpenAPI 기반의 API 문서를 자동으로 생성해주는 라이브러리입니다. 이 라이브러리는 API를 설명하는 문서와 인터랙티브한 UI를 제공하여, 개발자와 클라이언트가 API를 쉽게 이해하고 테스트할 수 있도록 도와줍니다.
drf-yasg
는 pip를 통해 간단하게 설치할 수 있습니다.
pip install drf-yasg
drf-yasg
를 프로젝트에 통합하려면, urls.py
파일에 필요한 설정을 추가해야 합니다.
urls.py
에 기본 설정 추가from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from django.urls import path
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 UI 접근
/swagger/
: Swagger UI를 통해 API 문서를 시각적으로 확인하고, 직접 API를 테스트할 수 있습니다./redoc/
: Redoc UI를 통해 API 문서를 좀 더 정적이고 포맷화된 형태로 확인할 수 있습니다.drf-yasg
의 openapi.Info
객체를 사용하여 API 문서의 기본 정보를 정의할 수 있습니다.
schema_view = get_schema_view(
openapi.Info(
title="My API",
default_version='v1',
description="This is a sample API for demonstration purposes",
terms_of_service="https://www.example.com/terms/",
contact=openapi.Contact(email="contact@example.com"),
license=openapi.License(name="Apache 2.0"),
),
public=True,
permission_classes=(permissions.AllowAny,),
각 URL 경로에 대한 스키마를 생성하기 위해 get_schema_view
함수를 사용합니다. with_ui
메서드를 통해 Swagger 또는 ReDoc UI를 렌더링할 수 있습니다.
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'),
]
drf-yasg
는 뷰 함수나 클래스에 직접 적용할 수 있는 데코레이터를 제공하여 문서화 과정을 더욱 세밀하게 제어할 수 있습니다.
swagger_auto_schema
데코레이터: 각 API 뷰에 대한 입력, 출력, 설명 등을 커스터마이징할 수 있습니다.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)
커스텀 스키마를 추가하거나, 특정 동작에 대한 API 문서를 추가로 작성할 수 있습니다.
from drf_yasg import openapi
class MyAPIView(APIView):
@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),
},
),
),
}
)
def get(self, request, pk=None):
data = {"id": pk, "name": f"Item {pk}"}
return Response(data)
파일 업로드 API를 문서화할 때는 swagger_auto_schema
를 사용하여 파일 파라미터를 정의할 수 있습니다.
from drf_yasg import openapi
class FileUploadView(APIView):
@swagger_auto_schema(
operation_description="Upload a file",
manual_parameters=[
openapi.Parameter(
'file', openapi.IN_FORM, description="Upload a file",
type=openapi.TYPE_FILE, required=True),
],
responses={200: 'File uploaded successfully'},
)
def post(self, request):
# 파일 처리 로직
return Response({"message": "File uploaded successfully"})
쿼리 파라미터를 명확하게 정의하여 API 문서에 반영할 수 있습니다.
class MyAPIView(APIView):
@swagger_auto_schema(
manual_parameters=[
openapi.Parameter('search', openapi.IN_QUERY, description="Search items", type=openapi.TYPE_STRING),
],
)
def get(self, request):
search_term = request.GET.get('search')
data = [{"id": 1, "name": "Item 1"}]
return Response(data)
drf-yasg
는 API 문서에 인증 정보(예: JWT, OAuth2)를 추가할 수 있습니다.
schema_view = get_schema_view(
openapi.Info(
title="My API",
default_version='v1',
),
public=True,
permission_classes=(permissions.AllowAny,),
authentication_classes=[...], # JWT 인증 클래스 추가 등
)
프로덕션 환경에서 drf-yasg
를 사용할 때는 문서 노출을 제어하거나, 캐시를 이용해 성능을 최적화할 수 있습니다.
from django.conf import settings
if settings.DEBUG:
urlpatterns += [
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]