Prompt Detail:
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:
- Install
drf-yasg
usingpip
:
pip install drf-yasg
- Add
'drf_yasg'
to yourINSTALLED_APPS
setting in your Django project'ssettings.py
file:
pythonINSTALLED_APPS = [
# ...
'drf_yasg',
]
- In your Django project's
urls.py
file, import theswagger
andschema
classes fromdrf_yasg.views
:
pythonfrom 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.Info
class to define your API's title, version, description, and other metadata. Thepublic=True
argument allows anyone to access the documentation, andpermission_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 (schema_view.with_ui('redoc', cache_timeout=0)
).Start your Django development server and navigate to
http://localhost:<port>/swagger/
orhttp://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.