drf-yasg: Swagger
drf-yasg (Yet Another Swagger Generator) is a popular Django package that generates Swagger/OpenAPI documentation for your Django REST framework APIs. It allows you to have a clean, interactive, and dynamic API documentation that makes it easy for developers to understand and test your API.
-
Install drf-yasg:
-
Add
drf_yasgto INSTALLED_APPS: -
Configure
drf-yasgin your project'surls.py:# Add the following to your project's urls.py: from django.urls import path, re_path, include from django.conf import settings from django.conf.urls.static import static from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Your API Title", default_version='v1', description="Your API description", terms_of_service="https://www.yourapp.com/terms/", contact=openapi.Contact(email="contact@yourapp.com"), license=openapi.License(name="Your License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ # ... your other URL patterns re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)Replace "Your API Title" and other information in the openapi.Info section with your actual API details.
-
Run your Django development server:
Now you can access the Swagger documentation by navigating to http://127.0.0.1:8000/swagger/ or http://127.0.0.1:8000/redoc/ in your web browser.
- The Swagger UI is available at the /swagger/ endpoint.
- The ReDoc UI is available at the /redoc/ endpoint.
-
Explore and Test Your API:
Once in the Swagger or ReDoc UI, you can explore your
API's endpoints, view the available methods, and even test your API directly from the interface.That's it! You've now integrated
drf-yasginto your Django project, providing interactive API documentation for your RESTful API.
Notes
Keep in mind Django Rest Swagger is now considered deprecated in favor of its successor, drf-yasg. You might want to consider using drf-yasg for newer projects. To use drf-yasg, follow my instructions above.