๐[Django] DRF Swagger header ์ค์ ํ๊ธฐ
Swagger?
Swagger
๋, ๊ฐ๋ฐํ REST API๋ฅผ ํธ๋ฆฌํ๊ฒ ๋ฌธ์ํ ํด์ฃผ๊ณ , ์ด๋ฅผ ํตํด์ ๊ด๋ฆฌ ๋ฐ ์ 3์ ์ฌ์ฉ์๊ฐ ํธ๋ฆฌํ๊ฒ API๋ฅผ ํธ์ถํด๋ณด๊ณ ํ
์คํธํ ์ ์๋ ๋๊ตฌ์.
DRF ์์ Swagger๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด drf-yasg
๋ฅผ ์ค์นํด์ค์ผํ๋ค.
drf_yasg
๋ Django๋ก ์ ์๋ API๋ฅผ ๋ฌธ์ํํ ์ ์๋ ํจํค์ง๋ก, Django Rest Framework_Yet Another Swagger Generator
์ ์ฝ์์.
์ธํ ์์
drf_yasg ์ค์น
$ pip install drf_yasg
settings.py ์ถ๊ฐ
INSTALLED_APPS = [
...
"rest_framework",
"drf_yasg",
]
urls.py ์ถ๊ฐ
urls.py
์๋ 3๋จ๊ณ๋ฅผ ๊ฑฐ์ณ ์ค์ ํด์ผํ๋ค.
-
get_schema_view/openapi/AllowAny import
from django.contrib import admin from django.urls import path, include from django.conf.urls import url from rest_framework.permissions import AllowAny from drf_yasg.views import get_schema_view from drf_yasg import openapi
-
schema_url_patterns (swagger์์ API ๋ฌธ์๋ก ๋ณด๊ณ ์ถ์ URL๋ค์ ์ ์ํจ)
schema_url_patterns = [ path('', include('blog.urls')), ] schema_view_v1 = get_schema_view( openapi.Info( title="Open API", default_version='v1', description="์์คํ API", terms_of_service="https://www.google.com/policies/terms/", ), public=True, permission_classes=(AllowAny,), patterns=schema_url_patterns, )
-
urlpatterns (Swagger๋ฅผ ๋ณด๊ธฐ ์ํ ์๋ํฌ์ธํธ ์ ์ํจ)
urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view_v1.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view_v1.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view_v1.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ]
API ๋ฐ์ฝ๋ ์ดํฐ ์ถ๊ฐ
DRF ์์๋ ์์ฒญํ request ๊ตฌ๋ถ์ API ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ํตํด ๊ตฌ๋ถํ๋ค. (FBV ๊ธฐ์ค)
- FBV: Function Based View โ API ์์ฒญ์ ์ฒ๋ฆฌํ ๋ถ๋ถ์ ํจ์๋ก ๊ตฌํ
FBV๋ฅผ ์ฌ์ฉํ ๋์๋ api_view(["GET"])
๊ณผ ๊ฐ์ด ์ ์ธํด์ค์ผํจ.
Swagger๋ฅผ ์ฌ์ฉํ ์๋ก์ด ํ ์คํธ ๊ธฐ๋ฅ?
HTTP ์์ฒญ์ ๋ณด๋ผ ๋, ํค๋ ๊ฐ์ ํฌํจ์์ผ์ผ ํ ๋๊ฐ ์๋ค.
์๋ฅผ ๋ค๋ฉด, ๋ก๊ทธ์ธ ๋ ํ์์ ๋ํด์๋ง ์ด๋ ํ ๋ทฐ๋ฅผ ๋ณด์ฌ์ค์ผ ํ ๋, ํค๋์ ํด๋น ์ ์ ๋ฅผ ๊ตฌ๋ถํ๋ ํ ํฐ ๊ฐ์ ๋ฃ๋๋ค๋์ง..
์ด๋ด ๋, Swagger UI์์ ์ง์ ํค๋์ ๊ฐ์ ๋ฃ๋ ๋ฐฉ๋ฒ์ ์ ์ฉํ ๊น?
๊ธฐ๋ณธ Swagger UI์๋ ์ด๋ฐ ์ญํ ์ ์๋ค.
์๋ ์ฝ๋๋ฅผ ์ถ๊ฐํ๋ฉด ๋จ.
์๋๋ accessToken
, refreshToken
๊ฐ์ ํค๋์ ํฌํจ์์ผ ์์ฒญ์ ๋ณด๋ผ ์ ์๋๋ก ํ๋ ์์์.
settings.py
SWAGGER_SETTINGS = {
'USE_SESSION_AUTH': False,
'SECURITY_DEFINITIONS': {
'AccessToken': {
'type': 'apiKey',
'in': 'header',
'name': 'Authorization',
'description': 'Add accessToken in format: Bearer <accessToken>',
},
'RefreshToken': {
'type': 'apiKey',
'in': 'header',
'name': 'Refresh-Token',
'description': 'Add refreshToken directly',
},
},
}
์ด ์ฝ๋๋ฅผ ์ถ๊ฐํ๋ฉด ๋จ!
๋๊ธ๋จ๊ธฐ๊ธฐ