What to expect from this article?
This article will cover implementing Swagger in a Django rest framework project; we will work on our accounts management
Series order
Check previous articles if interested!
- , but I'm open to suggestions if you know a better one!
Let's start with package installation
CODEpip install drf-yasg
now moving to our setting file
CODEINSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'drf_yasg', #new
'corsheaders',
'rest_framework',
'django_filters',
'app_account',
'app_admin',
'app_main',
]
SWAGGER_SETTINGS = {
'LOGIN_URL' : '/api/account/login/',
'SECURITY_DEFINITIONS': {
'Bearer': {
'type': 'apiKey',
'name': 'Authorization',
'in': 'header'
}
}
}
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}
alive_diary/settings.py
We have added the drf_yasg app to the installed apps and set the default authentication method to Bearer JWT token.
now to the URLs file
CODEfrom django.contrib import admin
from django.urls import path, include
from rest_framework.documentation import include_docs_urls # new
from rest_framework.schemas import get_schema_view # new
from drf_yasg.views import get_schema_view # new
from drf_yasg import openapi # new
schema_view = get_schema_view(
openapi.Info(
title="Swagger API",
default_version='v1',
),
public=True,
)
API_DESCRIPTION = 'A Web API for creating and editing.' # new
API_TITLE = 'API' # new
urlpatterns = [
path('admin/', admin.site.urls),
path('api/account/', include('app_account.urls')),
path('docs/', include_docs_urls(title=API_TITLE,description=API_DESCRIPTION)), # new
path('swagger/', schema_view.with_ui('swagger',cache_timeout=0),name="swagger-schema"), # new
]
that is it! great job!
let's try it
CODEpython manage.py runserver 0.0.0.0:8555
opening
http://localhost:8555/swagger/should look like
Then, we authenticate using the "Authorize" button at the top of the swagger page. Make sure to use the access token, and don't forget the Bearer in front of it: "Bearer token..."
it is empty! swagger wasn't able to recognize request schema, the easiest way to fit it is to use
we can test all authenticated requests using Swagger now! next article will go back to the accounts app
Stay tuned 😎
↗ Original-Artikel auf dev.to lesenVollständiger Original-BerichtAusführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
SOCIAL SHARE CARD GENERATOR