hotamul의 개발 이야기

[Django] drf_spectacular 사용해보기 본문

Dev./Django

[Django] drf_spectacular 사용해보기

hotamul 2022. 7. 13. 00:40

django, djangorestframework를 사용하여 api 서버를 만들어보기로 했다.

그리고 [Django] User Model 커스터마이징 #6 (TDD) 까지 진행해보면서 자동으로 api 문서를 작성할 수 있는 drf_spectacular에 대해 알게 되어 적용 해보려고 한다.

pip package 추가

나는 requirements.txt로 패키지 관리를 하고 있어서 requirements.txtdrf-spectacular 패키지를 추가해 주었다.

...
drf-spectacular>=0.15.1,<0.16

 

app, url 추가

이제 localhost:8000/api/docs url로 api 문서를 보기 위해 먼저 django 프로젝트 최상위 app/settings.py에 app을 추가한다.

# app/settings.py
...
INSTALLED_APPS = [
    ...
    'rest_framework',
    'drf_spectacular',
]

다음 app/urls.py에 아래와 같이 주소를 추가한다. api/schema는 schema를 다운로드 할 수 있는 url이다.

# app/urls.py
...
from drf_spectacular.views import (
    SpectacularAPIView,
    SpectacularSwaggerView,
)
...
urlpatterns = [
    ...
    path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'),
    path(
        'api/docs/',
        SpectacularSwaggerView.as_view(url_name='api-schema'),
        name='api-docs',
    ),
    ...
]

 

확인해보면 짜잔!

 

Comments