drf-yasg is a Python package that provides an easy way to generate Swagger/OpenAPI documentation for your Django REST Framework API. Here's how you can install and use
drf-yasg in your Django project:
pip install drf-yasg
INSTALLED_APPSsetting in your Django project's
INSTALLED_APPS = [ # ... 'drf_yasg', ]
- In your Django project's
urls.pyfile, import the
from django.urls import path 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://yourapi.com/terms/", contact=openapi.Contact(email="[email protected]"), license=openapi.License(name="MIT License"), ), public=True, permission_classes=[permissions.AllowAny], ) urlpatterns = [ # ... 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'), ]
This code sets up a schema view that uses the
openapi.Infoclass to define your API's title, version, description, and other metadata. The
public=Trueargument allows anyone to access the documentation, and
permission_classes=[permissions.AllowAny]specifies that no authentication is required to view the documentation.
Finally, you define two URLs: one for the Swagger UI (
schema_view.with_ui('swagger', cache_timeout=0)), and one for the ReDoc UI (
Start your Django development server and navigate to
http://localhost:<port>/redoc/to see your Swagger documentation.
You should see a Swagger UI page that displays all of your API endpoints, including their parameters, request and response formats, and examples. You can also use Swagger to test your API endpoints directly from the UI. ReDoc is another popular tool for generating API documentation, and it offers a more modern and responsive interface than Swagger UI.
drf-yasg offers many customization options for your documentation, such as adding custom authentication or pagination classes, and it's well-documented on its official website.