1 | initial version |
To set up drf-spectacular
in your Django project, you can follow these steps:
drf-spectacular
using pip:pip install drf-spectacular
drf_spectacular
to your INSTALLED_APPS in your project's settings.py file:INSTALLED_APPS = [
# other apps ...
"drf_spectacular",
]
drf_spectacular.urls
to your project's urls.py file:from django.urls import include, path
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
urlpatterns = [
# your project's urls ...
path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
path("api/schema/swagger-ui/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui"),
path("api/schema/redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc"),
]
Here, we're using the SpectacularAPIView
to serve the API schema, and the SpectacularSwaggerView
and SpectacularRedocView
to serve the Swagger UI and ReDoc documentation respectively.
DEFAULT_AUTO_SCHEMA_CLASS
to your project's settings.py file:REST_FRAMEWORK = {
# other settings ...
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}
This will configure drf-spectacular
to use its AutoSchema
class as the default schema generator for all your API views.
SpectacularSwaggerView
and SpectacularRedocView
to your CORS settings in your project's settings.py file:CORS_ALLOWED_ORIGINS = [
# other origins ...
"http://localhost:8080",
]
CORS_ALLOW_METHODS = [
# other methods ...
"GET",
]
CORS_ALLOW_HEADERS = [
# other headers ...
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
CORS_EXPOSE_HEADERS = [
# other headers ...
"content-disposition",
]
CORS_URLS_REGEX = r"^/api/schema/swagger-ui/.*|/api/schema/redoc/.*$"
This will allow CORS for the Swagger UI and ReDoc views.
http://localhost:8000/api/schema/swagger-ui/
or the ReDoc documentation at http://localhost:8000/api/schema/redoc/
.This should set up drf-spectacular
in your Django project and allow you to generate and view your API schema and documentation.