• DRF 프로젝트에서 API 문서 자동화 하기 (drf-yasg)

    2021. 5. 30.

    by. Jacob Lee

    728x90

     


     

    API 문서 자동화

    우선 API 문서를 왜 만들어야하고, 또 자동화가 왜 필요한지 이론적인 부분을 알아보았다.
    Swagger 공식 웹사이트 내용을 보면, 다음과 같이 나와있다.

    A critical component to providing a great developer experience 
    is providing accurate and up-to-date API documentation. 
    API documentation is the information that is required to 
    successfully consume and integrate with an API. 
    This could be in the form of technical writing, code samples, 
    and examples for better understanding how to consume an API.

    훌륭한 개발자 경험을 제공하기 위한 결정적인 부분은 바로 정확한 최신의 API 문서를 제공하는 것이다. 
    API 문서란 성공적으로 API를 사용하고 접목하기 위해 필요한 정보이다.
    이 것들은 테크니컬 라이팅, 코드 샘플, 또 어떻게 API를 사용할지 더 나은 이해를 위한 예시 같은 형태로 제공된다.

    캐나다에 있을 때 가끔 technical writer를 채용하는 것을 본 적 있는데, 보면서도 무슨 직업일까 했는데, 요번 기회에 약간 알 수 있었던 것 같다. 

    그럼 바로 drf에서 API 문서 자동화 하는 방법을 알아보자.

     

    drf-yasg

    우선 자세한 설치법은 공식 사이트에서 확인 가능하다.

     

    먼저 pip를 통해 drf-yasg를 설치한다.

    pip install drf-yasg

     

    그 다음 장고 INSTALLED_APP에 다음 부분을 추가한다.

    INSTALLED_APPS = [
       'drf_yasg',
    ]

     

    프로젝트 내의 `settings.py` 에 아래와 같이 입력해준다.

    from django.conf.urls import 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,),
    )
    
    urlpatterns = [
       path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
       path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
       path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
       ...
    ]

     

    공식 문서에 따르면 다음과 같이 총 4개의 엔드포인트가 생성된다.

    • A JSON view of your API specification at `/swagger.json`
    • A YAML view of your API specification at `/swagger.yaml`
    • swagger-ui view of your API specification at `/swagger/`
    • A ReDoc view of your API specification at `/redoc/`

     

    생성된 API 문서 확인

    위와 같이 세팅을 마친 프로젝트라면 아래와 같이 프로젝트-주소/swagger로 접속했을 때 아래와 같이 확인할 수 있다.

    앱별로, 리퀘스트 메소드 별로 정리된 API들

     

    개인적인 정보라 모자이크 처리를 했지만, 위처럼 앱 안에 HTTP 메소드 별로 나열이 되고, API url주소와 클래스 이름까지 포함된다.

     

    또한 API를 눌러 확장시키면, 다음과 같이 어떤 파라미터, 데이터 값이 필요한지 타입과 같이 표시되어지고, 또 어떤 응답이 올지도 확인할 수 있다.

    swagger 확장한 모습

     

    마치며

    사실 drf-yasg를 더 잘 사용할 수 있는 방법은 훨씬 더 많다.

    라이브러리를 다운 받아 example을 문서에 추가한다던지, 클래스의 독스토링을 추가함으로써 API에 더 자세한 설명을 추가할 수도 있다. 이렇게 API를 문서화 했을때, 또 swagger상에서 더욱 자세한 설명을 추가하거나 노션으로 또 따로 정리했을 때, 프론트와의 소통이 원할해지고 키 값의 이름, 데이터 속성등을 물어보는 시간 낭비가 없어지니 더욱 좋은 것 같다.

    728x90

    댓글