django swagger

GisangLee·2022년 6월 2일
0

my_module

목록 보기
19/33

1. Setting

pip install drf-yasg
INSTALLED_APPS = [
	...
    'drf_yasg',
]
  • config.urls.py
from drf_yasg import openapi
from drf_yasg.views import get_schema_view

schema_view = get_schema_view(
    openapi.Info(
        title="project name",
        default_version='프로젝트 버전 ( 1.0 )',
        description="API 문서",
        #terms_of_service="https://www.google.com/policies/terms/",
        #contact=openapi.Contact(email="이메일"), # 부가정보
        #license=openapi.License(name="mit"),     # 부가정보
    ),
    public=True,
    permission_classes=[permissions.AllowAny],
)

urlpatterns = [
    #path("admin/", admin.site.urls),
    path(r'api-v1/swagger(?P<format>\.json|\.yaml)', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    path(r'api-v1/swagger', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path(r'api-v1/redoc', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc-v1'),
    ...
    ...
    ..
    
]

2. API 별로 파라미터 설정하기

  • utils.py
def make_api_param(name, type, desc, format, default=""):
    param = openapi.Parameter(
        name,
        type,
        description=desc,
        type=format,
        default=default
    )

    return param


test_api_param = [
    make_api_param("author_pk", openapi.IN_QUERY, "소유자 PK", openapi.FORMAT_INT64),
    make_api_param("Authorization", openapi.IN_HEADER, "jwt", openapi.TYPE_STRING),
]
  • 호출하는 법
from drf_yasg.utils import swagger_auto_schema

class MyView(APIView):

    @swagger_auto_schema(manual_parameters=test_api_param)
    def get(self, request):

3. request Body 추가


""" Swagger 전용 """

class SwaggerTest(serializers.Serializer):
    author_pk = serializers.IntegerField(help_text="소유자 PK")
from drf_yasg.utils import swagger_auto_schema

class MyView(APIView):

    @swagger_auto_schema(request_body=SwaggerTest)
    def get(self, request):
profile
포폴 및 이력서 : https://gisanglee.github.io/web-porfolio/

0개의 댓글