drf-yasg Documentation

repository·master·Indexed 25 days ago

https://github.com/axnsan12/drf-yasg

A generator for Swagger/OpenAPI 2.0 specifications from Django Rest Framework APIs. It provides interactive documentation via Swagger UI and ReDoc, supports nested serializers, and includes built-in caching and validation. The library allows for extensive customization of the generated schema through the @swagger_auto_schema decorator, custom inspector classes (FieldInspector, SerializerInspector, FilterInspector, PaginatorInspector), and by subclassing SwaggerAutoSchema or OpenAPISchemaGenerator.

Tokens
17.4K
Snippets
23
Records
97
Agent score
85%

What's inside drf-yasg

  1. Understand OpenAPI 2.0 structure in drf-yasg

    master

    The library generates OpenAPI 2.0 documents. The structure follows the official Swagger/OpenAPI 2.0 specification:

    • Swagger Object: Root object containing info, schemes, securityDefinitions, paths, and definitions.
    • Paths: A mapping of {path} to PathItem objects. Each PathItem contains operations keyed by HTTP method (e.g., GET, POST).
    • Operation: Identified by (path, http_method). Contains parameters (query, header, form), responses (mapping of status codes to Response objects), operationId, and tags.
    • Definitions: A mapping of named models ({ModelName}) to Schema objects.

    Schema vs. Parameter

    FeatureSchemaParameter
    NestingCan nest other SchemasCannot nest other Parameters (except if in: body)
    File UploadsCannot describe file uploadsCan describe via type = file (only in form operations)
    ResponsesCan be used in ResponsesCannot be used in Responses
    Form OperationsCannot be used in form operationsCan be used in form operations
    ScopeRequest or response bodiesquery, form, header, or path parameters
  2. Quickstart: Configure drf-yasg in Django

    master

    To set up drf-yasg, follow these two steps:

    1. Update settings.py

    Add drf_yasg and django.contrib.staticfiles to your INSTALLED_APPS. staticfiles is required to serve the Swagger UI CSS and JS files.

    INSTALLED_APPS = [
        ...
        'django.contrib.staticfiles',
        'drf_yasg',
        ...
    ]

    2. Update urls.py

    Define a schema_view using get_schema_view and add the corresponding paths to your urlpatterns to expose JSON, YAML, Swagger UI, and ReDoc endpoints.

    from django.urls import re_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="Snippets API",
            default_version='v1',
            description="Test description",
            terms_of_service="https://www.google.com/policies/terms/",
            contact=openapi.Contact(email="contact@snippets.local"),
            license=openapi.License(name="BSD License"),
        ),
        public=True,
        permission_classes=(permissions.AllowAny,)
    )
    
    urlpatterns = [
        path('swagger.<format>/', 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'),
        ...
    ]
  3. Configure swagger-ui as an OAuth2 client

    master

    You can configure swagger-ui to act as an OAuth2 client for testing "Try it out" requests. This requires both a SECURITY_DEFINITIONS entry of type oauth2 and an OAUTH2_CONFIG dictionary in SWAGGER_SETTINGS.

    Note: If your OAuth2 provider requires an absolute redirect URL, you can override the default redirect path using the OAUTH2_REDIRECT_URL setting. The default is <origin>/static/drf-yasg/swagger2-ui-dist/oauth2-redirect.html.

    SWAGGER_SETTINGS = {
       'USE_SESSION_AUTH': False,
       'SECURITY_DEFINITIONS': {
          'Your App API - Swagger': {
             'type': 'oauth2',
             'authorizationUrl': '/yourapp/o/authorize',
             'tokenUrl': '/yourapp/o/token/',
             'flow': 'accessCode',
             'scopes': {
              'read:groups': 'read groups',
             }
          }
       },
       'OAUTH2_CONFIG': {
          'clientId': 'yourAppClientId',
          'clientSecret': 'yourAppClientSecret',
          'appName': 'your application name'
       },
    }
  4. Configure URL settings in drf-yasg

    master

    Settings that configure URLs (such as LOGIN_URL, SPEC_URL, or VALIDATOR_URL) accept several input formats to allow for flexible URL resolution. You can provide:

    • A view name: A string that will be passed to urls.reverse().
    • A 2-tuple: (view_name, kwargs) where kwargs is a dictionary used for reverse-resolution.
    • A 3-tuple: (view_name, args, kwargs) where args is a tuple/list and kwargs is a dictionary.
    • A URL: A raw string URL which will be used as-is without resolution.
  5. Install drf-yasg

    master

    Install the core package via PyPI:

    pip install --upgrade drf-yasg

    If you want to use the built-in validation mechanisms (e.g., validators=['ssv']), install the validation extra:

    pip install --upgrade drf-yasg[validation]
    pip install --upgrade drf-yasg
  6. How drf-yasg generates API documentation by default

    master

    The library automatically inspects your Django Rest Framework (DRF) setup to build the schema:

    • Paths: Generated by exploring patterns in your urlconf. Only views inheriting from DRF's APIView are processed.
    • Path Parameters: Extracted from URL template parameters. Types are guessed from the view's queryset and lookup_field.
    • Query Parameters: Generated from the view's filter_backends and paginator.
    • Request Body: Generated for POST, PUT, and PATCH methods using the view's serializer_class.
      • If the view uses multipart/form-data or application/x-www-form-urlencoded, the body is output as form parameters.
      • Otherwise, it is output as a single body parameter wrapping a Schema.
    • Responses:
      • If responses are manually provided via @swagger_auto_schema, those are used.
      • Otherwise, a default success code is assumed (204 for DELETE, 201 for POST, 200 for others).
      • For list views or paginated views, the response schema is automatically wrapped in an array or paging structure.
    • Descriptions: Picked up from docstrings and help_text attributes.
  7. Customize the Swagger UI and ReDoc web interfaces

    master

    You can customize the appearance and behavior of the web UI using settings defined in SWAGGER_SETTINGS and REDOC_SETTINGS.

    For deeper customization, you can extend the default templates used for rendering:

    • drf_yasg/swagger-ui.html
    • drf_yasg/redoc.html

    If you need to modify advanced functionality in Swagger UI, you can review and hook into the JavaScript logic found in drf_yasg/swagger-ui-init.js.

  8. Configure security requirements for endpoints

    master

    After defining security schemes, you must specify which schemes apply to your endpoints.

    1. Global Requirements: By default, drf-yasg generates a top-level security requirement that accepts any one of your declared definitions. You can override this globally using the SECURITY_REQUIREMENTS setting in SWAGGER_SETTINGS.
    2. Operation-level Overrides: To specify security for a specific endpoint, use the security parameter within the @swagger_auto_schema decorator.
  9. Customize methods using Django's method_decorator

    master

    If you want to customize a method that you are not implementing yourself (e.g., a method from a base class in a ModelViewSet), use Django's method_decorator in combination with swagger_auto_schema. This avoids the need to manually override the method.

    @method_decorator(name='list', decorator=swagger_auto_schema(
        operation_description="description from swagger_auto_schema via method_decorator"
    ))
    class ArticleViewSet(viewsets.ModelViewSet):
        ...
  10. Exclude endpoints from Swagger documentation

    master

    To prevent a view from appearing in the Swagger UI, you can either set the class-level swagger_schema attribute to None (which excludes all methods of that class) or use the @swagger_auto_schema decorator with auto_schema=None to exclude specific HTTP methods.

    class UserList(APIView):
       swagger_schema = None
    
       # all methods of the UserList class will be excluded
       ...
    
    # only the GET method will be shown in Swagger
    @swagger_auto_schema(method='put', auto_schema=None)
    @swagger_auto_schema(methods=['get'], ...)
    @api_view(['GET', 'PUT'])
    def user_detail(request, pk):
        pass
  11. Integrate with djangorestframework-camel-case

    master
    Integration with djangorestframework-camel-case is supported out of the box. If the package is installed and your APIView uses CamelCaseJSONParser or CamelCaseJSONRenderer, all property names will be converted to camelCase by default in the generated schema.