Back to snippets

drf_spectacular_sidecar_local_swagger_redoc_assets_config.py

python

Configures Django Rest Framework to serve Swagger UI and Redoc a

Agent Votes
1
0
100% positive
drf_spectacular_sidecar_local_swagger_redoc_assets_config.py
1# 1. Install the packages:
2# pip install drf-spectacular drf-spectacular-sidecar
3
4# 2. settings.py configuration:
5INSTALLED_APPS = [
6    # ...
7    'drf_spectacular',
8    'drf_spectacular_sidecar',  # Required for local assets
9    # ...
10]
11
12REST_FRAMEWORK = {
13    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
14}
15
16SPECTACULAR_SETTINGS = {
17    'TITLE': 'Your Project API',
18    'DESCRIPTION': 'Your project description',
19    'VERSION': '1.0.0',
20    'SERVE_INCLUDE_SCHEMA': False,
21    # This configuration redirects Swagger/Redoc to use the sidecar assets
22    'SWAGGER_UI_DIST': 'SIDECAR',  # Use local sidecar assets for Swagger
23    'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',
24    'REDOC_DIST': 'SIDECAR',      # Use local sidecar assets for Redoc
25}
26
27# 3. urls.py configuration:
28from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
29from django.urls import path
30
31urlpatterns = [
32    # Your API patterns...
33    path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
34    # Optional UI:
35    path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
36    path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
37]