### Setting Up and Running DRF-YASG Example Project Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This sequence of commands provides a complete guide to setting up and running the `drf-yasg` example project. It covers cloning the repository, navigating to the project directory, creating and activating a virtual environment, installing dependencies, running database migrations, starting the Django development server, and accessing the generated Swagger UI in a browser. ```console $ git clone https://github.com/axnsan12/drf-yasg.git $ cd drf-yasg $ virtualenv venv $ source venv/bin/activate (venv) $ cd testproj (venv) $ python -m pip install --upgrade pip setuptools (venv) $ pip install --upgrade -r requirements.txt (venv) $ python manage.py migrate (venv) $ python manage.py runserver (venv) $ firefox localhost:8000/swagger/ ``` -------------------------------- ### Setting Up drf-yasg Development Environment (Console) Source: https://github.com/axnsan12/drf-yasg/blob/master/CONTRIBUTING.rst This snippet demonstrates how to create a Python virtual environment, activate it, and install the drf-yasg package in editable development mode along with its validation and development dependencies. This setup is crucial for local development and testing. ```console $ python -m venv venv $ source venv/bin/activate (venv) $ python -m pip install -U pip setuptools (venv) $ pip install -U -e '.[validation]' (venv) $ pip install -U -r requirements/dev.txt ``` -------------------------------- ### Running drf-yasg Test Project (Console) Source: https://github.com/axnsan12/drf-yasg/blob/master/CONTRIBUTING.rst This snippet shows how to navigate into the `testproj` directory, apply database migrations, start the Django development server, and then access the generated Swagger UI in a web browser. This allows developers to visually verify their changes against the test project. ```console (venv) $ cd testproj (venv) $ python manage.py migrate (venv) $ python manage.py runserver (venv) $ firefox localhost:8000/swagger/ ``` -------------------------------- ### Installing drf-yasg via pip Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This command installs the `drf-yasg` library from PyPI, upgrading it if an older version is already present. It is the standard and preferred method for installing the package. ```console pip install --upgrade drf-yasg ``` -------------------------------- ### Installing drf-yasg with Validation Dependencies Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This command installs `drf-yasg` along with its optional dependencies required for built-in schema validation. This is necessary if you plan to use the validation features provided by the library. ```console pip install --upgrade drf-yasg[validation] ``` -------------------------------- ### Validating OpenAPI Specification with Swagger CLI Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This snippet demonstrates how to install and use `swagger-cli` to validate an OpenAPI specification. It shows the global installation via npm and then validates a remote `swagger.yaml` file, confirming its syntactic validity at the JSON schema level. ```console $ npm install -g swagger-cli $ swagger-cli validate http://test.local:8002/swagger.yaml ``` -------------------------------- ### Running drf-yasg Tests and Linting (Console) Source: https://github.com/axnsan12/drf-yasg/blob/master/CONTRIBUTING.rst This snippet provides commands for running tests and linting checks. It covers installing test dependencies, executing pytest for unit and integration tests with coverage, and optionally running `isort` for import sorting and `flake8` for code style and quality checks. `tox` is also shown for running tests across multiple Python environments. ```console # install test dependencies (venv) $ pip install -U -r requirements/test.txt # run tests in the current environment, faster than tox (venv) $ pytest -n auto --cov # (optional) sort imports with isort and check flake8 linting (venv) $ isort --apply (venv) $ flake8 src/drf_yasg testproj tests setup.py # (optional) run tests for other python versions in separate environments (venv) $ tox ``` -------------------------------- ### Setting Default Model Rendering in Swagger UI (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting determines whether operations in Swagger UI show the model structure or an example value by default. `'model'` displays the model fields, while `'example'` shows the example value. It maps to the `defaultModelRendering` parameter. ```python 'model' ``` -------------------------------- ### Customizing Class-Based API Views with @swagger_auto_schema (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst Illustrates how to decorate individual HTTP method handlers (e.g., 'get', 'post') within a class-based 'APIView' to customize their Swagger documentation, such as defining responses or operation descriptions. ```python class UserList(APIView): @swagger_auto_schema(responses={200: UserSerializer(many=True)}) def get(self, request): ... @swagger_auto_schema(operation_description="description") def post(self, request): ... ``` -------------------------------- ### Configuring Swagger and ReDoc Settings in Django Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This snippet demonstrates how to define `SWAGGER_SETTINGS` and `REDOC_SETTINGS` in a Django `settings.py` file to customize the behavior of the Swagger UI and ReDoc documentation. It includes an example of setting a basic security definition for Swagger and disabling lazy rendering for ReDoc. ```Python SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'basic': { 'type': 'basic' } }, ... } REDOC_SETTINGS = { 'LAZY_RENDERING': False, ... } ``` -------------------------------- ### Inferring SerializerMethodField Schema with Type Hinting in Python Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This example shows how drf-yasg can infer the schema for a SerializerMethodField using Python 3 type hints. By specifying the return type (e.g., -> float), the library automatically generates the correct OpenAPI schema for the field. ```python class SomeSerializer(serializers.Serializer): some_number = serializers.SerializerMethodField() def get_some_number(self, obj) -> float: return 1.0 ``` -------------------------------- ### Customizing Function-Based API Views with @swagger_auto_schema (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst Shows how to apply '@swagger_auto_schema' multiple times to a function-based view to customize different HTTP methods. It demonstrates adding manual parameters and defining custom responses for specific methods (GET, PUT, POST). ```python from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework.decorators import api_view from drf_yasg import openapi test_param = openapi.Parameter('test', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_BOOLEAN) user_response = openapi.Response('response description', UserSerializer) # 'method' can be used to customize a single HTTP method of a view @swagger_auto_schema(method='get', manual_parameters=[test_param], responses={200: user_response}) # 'methods' can be used to apply the same modification to multiple methods @swagger_auto_schema(methods=['put', 'post'], request_body=UserSerializer) @api_view(['GET', 'PUT', 'POST']) def user_detail(request, pk): ... ``` -------------------------------- ### Decorating as_view Result with swagger_auto_schema in Python Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This example shows how to directly decorate the result of a view's as_view() method with swagger_auto_schema. It configures the POST method's responses for a login view, allowing for OpenAPI schema customization without subclassing the view. ```python decorated_login_view = \ swagger_auto_schema( method='post', responses={status.HTTP_200_OK: LoginResponseSerializer} )(LoginView.as_view()) urlpatterns = [ ... url(r'^login/$', decorated_login_view, name='login') ] ``` -------------------------------- ### Configuring Swagger UI as an OAuth2 Client in drf-yasg (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/security.rst This example illustrates how to set up `SWAGGER_SETTINGS` for `swagger-ui` to act as an OAuth2 client. It defines an OAuth2 security scheme within `SECURITY_DEFINITIONS` specifying authorization and token URLs, flow type, and scopes. Additionally, `OAUTH2_CONFIG` is used to provide client credentials and application name for the OAuth2 interaction. ```Python 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' } } ``` -------------------------------- ### Adding Descriptions to DjangoFilterBackend Parameters with FilterInspector (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This example shows how to implement a custom FilterInspector (DjangoFilterDescriptionInspector) to automatically add descriptive text to parameters generated by DjangoFilterBackend. It iterates through filter parameters, populating their description attribute if it's empty, and demonstrates how to apply this inspector to a ModelViewSet using the @swagger_auto_schema decorator. ```Python class DjangoFilterDescriptionInspector(CoreAPICompatInspector): def get_filter_parameters(self, filter_backend): if isinstance(filter_backend, DjangoFilterBackend): result = super(DjangoFilterDescriptionInspector, self).get_filter_parameters(filter_backend) for param in result: if not param.get('description', ''): param.description = "Filter the returned list by {field_name}".format(field_name=param.name) return result return NotHandled @method_decorator(name='list', decorator=swagger_auto_schema( filter_inspectors=[DjangoFilterDescriptionInspector] )) class ArticleViewSet(viewsets.ModelViewSet): filter_backends = (DjangoFilterBackend,) filterset_fields = ('title',) ... ``` -------------------------------- ### Customizing Operation IDs to Camel Case with SwaggerAutoSchema (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This snippet demonstrates subclassing SwaggerAutoSchema to customize the generation of OpenAPI operation IDs. It overrides the get_operation_id method to convert generated IDs to camel case, providing an example of how to apply this custom schema class globally via SWAGGER_SETTINGS. This allows for consistent operation ID formatting across the API documentation. ```Python from inflection import camelize class CamelCaseOperationIDAutoSchema(SwaggerAutoSchema): def get_operation_id(self, operation_keys): operation_id = super(CamelCaseOperationIDAutoSchema, self).get_operation_id(operation_keys) return camelize(operation_id, uppercase_first_letter=False) SWAGGER_SETTINGS = { 'DEFAULT_AUTO_SCHEMA_CLASS': 'path.to.CamelCaseOperationIDAutoSchema', ... } ``` -------------------------------- ### Configuring Nested Serializer References in drf-yasg (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This example illustrates how to explicitly define a serializer for a nested field (`child` in `AnotherSerializer`) instead of letting `ModelSerializer` automatically generate one. This ensures that the nested field is output by reference in the OpenAPI schema, which is crucial for `ForeignKey` fields if by-reference behavior is desired. It depends on `Django REST Framework` serializers. ```python class OneSerializer(serializers.ModelSerializer): class Meta: model = SomeModel fields = ('id',) class AnotherSerializer(serializers.ModelSerializer): child = OneSerializer() class Meta: model = SomeParentModel fields = ('id', 'child') ``` -------------------------------- ### Adding Custom Validators to Overridden JSONField (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This example illustrates how to manually re-add validators to a custom JSONField (like EmailMessageField) after overriding a default field generated by a ModelSerializer. It shows setting the default_validators attribute to include a custom validator, addressing the loss of automatic validation when custom fields are used. ```Python class EmailMessageField(serializers.JSONField): default_validators = [my_custom_email_validator] ... ``` -------------------------------- ### Displaying generate_swagger Command Help (Console) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/rendering.rst This console command demonstrates how to access the help documentation for the `generate_swagger` management command. It provides information on available options and arguments for advanced usage of the schema generation tool. ```console $ python manage.py generate_swagger --help usage: manage.py generate_swagger [-h] [--version] [-v {0,1,2,3}] ... more options ... ``` -------------------------------- ### Building drf-yasg Documentation (Console) Source: https://github.com/axnsan12/drf-yasg/blob/master/CONTRIBUTING.rst This command uses `tox` to build the project documentation. It's essential for verifying that documentation changes are correctly rendered and free of errors before submitting a pull request. ```console (venv) $ tox -e docs ``` -------------------------------- ### Defining API Info and Schema View in urls.py (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/rendering.rst This `urls.py` snippet shows how to define an `openapi.Info` object (`api_info`) containing API metadata. It also demonstrates how to use `get_schema_view` without explicitly passing the `info` argument, as it will be automatically retrieved from the `DEFAULT_INFO` setting configured in `settings.py`. ```python api_info = openapi.Info( title="Snippets API", ... other arguments ... ) schema_view = get_schema_view( # the info argument is no longer needed here as it will be picked up from DEFAULT_INFO ... other arguments ... ) ``` -------------------------------- ### Generating Swagger Spec File (Console) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/rendering.rst This command-line snippet shows how to use the `generate_swagger` management command to create a Swagger spec file (e.g., `swagger.json`) without needing to run the Django web server. This is useful for static file generation or CI/CD pipelines. ```console $ python manage.py generate_swagger swagger.json ``` -------------------------------- ### Defining Supported HTTP Submit Methods for Swagger UI (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This list specifies which HTTP methods have the 'Try it out' feature enabled in Swagger UI. An empty array disables this feature for all operations. It does not filter operations from display. It maps to the `supportedSubmitMethods` parameter. ```python ['get','put','post','delete','options','head','patch','trace'] ``` -------------------------------- ### Configuring DEFAULT_INFO in Django Settings (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/rendering.rst This Python snippet for `settings.py` illustrates how to define the `DEFAULT_INFO` setting within `SWAGGER_SETTINGS`. This setting specifies the import path to an `openapi.Info` object, allowing the `generate_swagger` command to automatically pick up API metadata. ```python SWAGGER_SETTINGS = { 'DEFAULT_INFO': 'import.path.to.urls.api_info', } ``` -------------------------------- ### Generating Client Code with Swagger Codegen CLI Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This command illustrates how to use `swagger-codegen-cli` via a Docker container to generate client-side code. It specifies an input OpenAPI definition file (`reference.yaml`), the target language (`javascript`), and an output directory for the generated code. ```console $ docker run --rm -v ${PWD}:/local swaggerapi/swagger-codegen-cli generate -i /local/tests/reference.yaml -l javascript -o /local/.codegen/js ``` -------------------------------- ### Running Local Swagger Validator with Docker and Testing Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This console snippet provides commands to run a local Swagger validator using Docker and then test it with `curl`. It shows how to launch the `swaggerapi/swagger-validator` container and subsequently query its debug endpoint to validate a local API schema, ensuring offline validation capabilities. ```console $ docker run --name swagger-validator -d -p 8189:8080 --add-host test.local:10.0.75.1 swaggerapi/swagger-validator 84dabd52ba967c32ae6b660934fa6a429ca6bc9e594d56e822a858b57039c8a2 $ curl http://localhost:8189/debug?url=http://test.local:8002/swagger/?format=openapi {} ``` -------------------------------- ### Fetching OpenAPI Schema with Query Parameters in ReDoc (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting, when `True`, fetches the OpenAPI document using the query parameters passed to the ReDoc page request. It maps to a ReDoc parameter. ```python True ``` -------------------------------- ### Positioning Path and HTTP Verb in ReDoc (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting, when `True`, displays the path link and HTTP verb in the middle panel of ReDoc instead of the right panel. It maps to the `pathInMiddlePanel` attribute. ```python False ``` -------------------------------- ### Defining Basic and Bearer Token Security Schemes in drf-yasg (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/security.rst This snippet demonstrates how to configure `SWAGGER_SETTINGS` to define security schemes for HTTP Basic Authentication and API Key (Bearer token) authentication. It uses the `SECURITY_DEFINITIONS` dictionary to specify the type and parameters for each scheme, making them available for use in Swagger UI. ```Python SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Basic': { 'type': 'basic' }, 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header' } } } ``` -------------------------------- ### Regenerating drf-yasg Reference Schema (Console) Source: https://github.com/axnsan12/drf-yasg/blob/master/CONTRIBUTING.rst This command regenerates the `tests/reference.yaml` file, which contains the expected schema output for testing. It's used when changes affect the API schema, ensuring the reference is up-to-date for comparison during tests. The `--overwrite` flag forces an update, and `--user` and `--url` specify authentication and the base URL for schema generation. ```console (venv) $ python testproj/manage.py generate_swagger tests/reference.yaml --overwrite --user admin --url http://test.local:8002/ ``` -------------------------------- ### Configuring drf-yasg in Django settings.py Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This snippet demonstrates how to add `drf_yasg` to the `INSTALLED_APPS` list in your Django `settings.py` file. `django.contrib.staticfiles` is also required to serve the static assets for Swagger UI and Redoc. ```python INSTALLED_APPS = [ ... 'django.contrib.staticfiles', # required for serving swagger ui's css/js files 'drf_yasg', ... ] ``` -------------------------------- ### DRF-YASG Swagger/Redoc Page Template (Django Template) Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/swagger-ui.html This comprehensive Django template provides the complete structure for rendering the Swagger UI or Redoc documentation page. It includes static file loading, defines various customizable blocks for HTML elements (head, styles, scripts, body), dynamically injects Swagger and OAuth2 configurations, and implements conditional logic for Django's session authentication, allowing users to log in/out directly from the documentation interface. ```Django Template Language {% load static %} {% block title %}{{ title }}{% endblock %} {% block extra_head %} {# -- Add any extra HTML heads tags here - except scripts and styles -- #} {% endblock %} {% block favicon %} {# -- Maybe replace the favicon -- #} {% endblock %} {% block main_styles %} {% endblock %} {% block extra_styles %} {# -- Add any additional CSS scripts here -- #} {% endblock %} {% block extra_body %} {# -- Add any header/body markup here (rendered BEFORE the swagger-ui/redoc element) -- #} {% endblock %} {% block footer %} {# -- Add any footer markup here (rendered AFTER the swagger-ui/redoc element) -- #} {% endblock %} {{ swagger_settings | safe }} {{ oauth2_config | safe }} {% block main_scripts %} {% endblock %} {% block extra_scripts %} {# -- Add any additional scripts here -- #} {% endblock %} []({% static 'drf-yasg/swagger-ui-dist/oauth2-redirect.html' %}){% if USE_SESSION_AUTH %} {% block session_auth_button %} {% csrf_token %} {% block user_context_message %} {% if request.user.is_authenticated %} Django {{ request.user }} {% endif %} {% endblock %} {% if request.user.is_authenticated %} [{% block django_logout_message %} Django Logout {% endblock %}]({{ LOGOUT_URL }}?next={{ request.path }}) {% else %} [{% block django_login_message %} Django Login {% endblock %}]({{ LOGIN_URL }}?next={{ request.path }}) {% endif %} {% endblock %} {% endif %} ``` -------------------------------- ### Setting up drf-yasg Schema Views in Django urls.py Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This snippet configures the `drf-yasg` schema views in your Django `urls.py`. It defines an `openapi.Info` object for API metadata and sets up three URL paths: one for the raw JSON/YAML schema, one for the Swagger UI, and one for Redoc, making the API documentation accessible. ```python from django.urls import re_path, 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./', 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') ] ``` -------------------------------- ### Subclassing SchemaView for Customization (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/rendering.rst This snippet demonstrates how to extend the `SchemaView` class, which is returned by `get_schema_view`, to customize its behavior. It shows how to override the `generator_class` and `renderer_classes` properties to use custom logic for schema generation and rendering. ```python SchemaView = get_schema_view(info, ...) class CustomSchemaView(SchemaView): generator_class = CustomSchemaGenerator renderer_classes = (CustomRenderer1, CustomRenderer2,) ``` -------------------------------- ### Ordering Required Properties First in ReDoc (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting, when `True`, displays required properties first in ReDoc, ordered as they appear in the required array. It maps to the `requiredPropsFirst` attribute. ```python False ``` -------------------------------- ### Setting OpenAPI Specification URL for ReDoc (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting specifies the URL pointing to an OpenAPI document for ReDoc. If `None`, ReDoc appends `?format=openapi` to the UI's URL. It maps to the `spec-url` attribute. ```python None ``` -------------------------------- ### Enabling Lazy Rendering Mode in ReDoc (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting enables lazy rendering mode in ReDoc, useful for APIs with many operations. It renders the initial screen quickly and then asynchronously renders the rest. Note: This feature might be removed in future ReDoc versions. It maps to the `lazyRendering` attribute. ```python False ``` -------------------------------- ### Configuring Basic Security Definition in DRF-YASG (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This snippet defines a default basic authentication security scheme for the OpenAPI specification. It specifies the type as 'basic', which is a common method for simple username/password authentication. This definition can be referenced by SECURITY_REQUIREMENTS to enforce authentication globally or per operation. ```Python 'basic': { 'type': 'basic' } ``` -------------------------------- ### Configuring Swagger UI to Show Extensions (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting controls the display of vendor extension (x-..) fields in the Swagger UI. When set to `True`, these fields will be visible. It maps to the `showExtensions` parameter in Swagger UI. ```python True ``` -------------------------------- ### Handling Swagger UI OAuth2 Redirect in JavaScript Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/static/drf-yasg/swagger-ui-dist/oauth2-redirect.html This JavaScript function `run` is executed on page load to process the OAuth2 redirect. It parses URL parameters (hash or search string) to extract authorization codes, tokens, or error messages. It validates the `state` parameter against the original `sentState` to prevent CSRF and then invokes the appropriate callback (`oauth2.callback` or `oauth2.errCb`) in the opener window, passing the authentication details. It supports both authorization code and implicit flows. ```JavaScript 'use strict'; function run () { var oauth2 = window.opener.swaggerUIRedirectOauth2; var sentState = oauth2.state; var redirectUrl = oauth2.redirectUrl; var isValid, qp, arr; if (/code|token|error/.test(window.location.hash)) { qp = window.location.hash.substring(1).replace('?', '&'); } else { qp = location.search.substring(1); } arr = qp.split("&"); arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"'; }); qp = qp ? JSON.parse('{' + arr.join() + '}', function (key, value) { return key === "" ? value : decodeURIComponent(value); } ) : {}; isValid = qp.state === sentState; if (( oauth2.auth.schema.get("flow") === "accessCode" || oauth2.auth.schema.get("flow") === "authorizationCode" || oauth2.auth.schema.get("flow") === "authorization_code" ) && !oauth2.auth.code) { if (!isValid) { oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "warning", message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server." }); } if (qp.code) { delete oauth2.state; oauth2.auth.code = qp.code; oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl}); } else { let oauthErrorMsg; if (qp.error) { oauthErrorMsg = "["+qp.error+"]: " + (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") + (qp.error_uri ? "More info: "+qp.error_uri : ""); } oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "error", message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server." }); } } else { oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl}); } window.close(); } if (document.readyState !== 'loading') { run(); } else { document.addEventListener('DOMContentLoaded', function () { run(); }); } ``` -------------------------------- ### Injecting ReDoc Settings in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This snippet safely renders the `redoc_settings` variable, which typically contains configuration options for the ReDoc documentation viewer. The `| safe` filter prevents Django from escaping the HTML, allowing raw HTML/JSON to be injected. ```Django Template Language {{ redoc_settings | safe }} ``` -------------------------------- ### Configuring OAuth2 Parameters for Swagger UI (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting provides OAuth2 configuration parameters to the `SwaggerUIBundle#initOAuth` method. It must be a dictionary and allows detailed customization of OAuth2 authentication. It maps to the `oauth2Config` parameter. ```python {} ``` -------------------------------- ### Displaying Common Extensions in Swagger UI Parameters (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting controls the display of common extensions (like `pattern`, `maxLength`, `minLength`, `maximum`, `minimum`) for Parameters in Swagger UI. When `True`, these fields and their values are shown. It maps to the `showCommonExtensions` parameter. ```python True ``` -------------------------------- ### Configuring Default Expanded Responses in ReDoc (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting specifies which responses to expand by default in ReDoc, based on response codes (e.g., '200,201'). The special value 'all' expands all responses, but can slow down rendering. It maps to the `expandResponses` attribute. ```python 'all' ``` -------------------------------- ### Customizing ViewSet Actions with @swagger_auto_schema (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst Demonstrates applying '@swagger_auto_schema' to custom '@action' methods within a 'ModelViewSet'. It shows how to customize single-method actions (e.g., 'today') and multi-method actions (e.g., 'image') by decorating each HTTP method separately, as well as standard 'update' and 'partial_update' methods. ```python class ArticleViewSet(viewsets.ModelViewSet): # method or 'methods' can be skipped because the action only handles a single method (GET) @swagger_auto_schema(operation_description='GET /articles/today/') @action(detail=False, methods=['get']) def today(self, request): ... @swagger_auto_schema(method='get', operation_description="GET /articles/{id}/image/") @swagger_auto_schema(method='post', operation_description="POST /articles/{id}/image/") @action(detail=True, methods=['get', 'post'], parser_classes=(MultiPartParser,)) def image(self, request, id=None): ... @swagger_auto_schema(operation_description="PUT /articles/{id}/") def update(self, request, *args, **kwargs): ... @swagger_auto_schema(operation_description="PATCH /articles/{id}/") def partial_update(self, request, *args, **kwargs): ... ``` -------------------------------- ### Loading Static Files in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This snippet loads the `static` tag library, which is essential for referencing static assets (like CSS, JavaScript, images) within Django templates. It allows the use of the `{% static %}` tag. ```Django Template Language {% load static %} ``` -------------------------------- ### Using Native Scrollbars in ReDoc Sidemenu (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting, when `True`, uses native scrollbars for the ReDoc sidemenu instead of `perfect-scroll`, which can improve scrolling performance for large specifications. It maps to the `nativeScrollbars` attribute. ```python False ``` -------------------------------- ### Using swagger_serializer_method for SerializerMethodField in Python Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This snippet illustrates using the swagger_serializer_method decorator to explicitly define the schema for SerializerMethodField instances. It demonstrates how to specify a serializer class or instance (including many=True for lists) to correctly represent the field's output in the generated OpenAPI schema. ```python from drf_yasg.utils import swagger_serializer_method class OtherStuffSerializer(serializers.Serializer): foo = serializers.CharField() class ParentSerializer(serializers.Serializer): other_stuff = serializers.SerializerMethodField() many_other_stuff = serializers.SerializerMethodField() @swagger_serializer_method(serializer_or_field=OtherStuffSerializer) def get_other_stuff(self, obj): return OtherStuffSerializer().data @swagger_serializer_method(serializer_or_field=OtherStuffSerializer(many=True)) def get_many_other_stuff(self, obj): return OtherStuffSerializer().data ``` -------------------------------- ### Setting OAuth2 Redirect URL for Swagger UI (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting is used for OAuth2 authentication with Swagger UI. If `None`, the `oauth2RedirectUrl` parameter defaults to the static `oauth2-redirect.html` file provided by Swagger UI. It maps to the `oauth2RedirectUrl` parameter. ```python None ``` -------------------------------- ### Applying swagger_auto_schema with method_decorator in Python Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This snippet demonstrates how to apply swagger_auto_schema to a specific method of a ModelViewSet using Django's method_decorator. This approach allows customizing the OpenAPI operation description for the 'list' action without explicitly overriding the method in the viewset. ```python @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="description from swagger_auto_schema via method_decorator" )) class ArticleViewSet(viewsets.ModelViewSet): ... ``` -------------------------------- ### Adding Extra Body Markup (Pre-Content) in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This block provides a hook for injecting custom HTML markup into the `` section of the page, specifically before the main Swagger UI or ReDoc element is rendered. It's suitable for headers or introductory content. ```Django Template Language {% block extra_body %} {# -- Add any header/body markup here (rendered BEFORE the swagger-ui/redoc element) -- #} {% endblock %} ``` -------------------------------- ### Main Scripts Block in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This block is reserved for the primary JavaScript files or inline scripts required by the documentation page. It serves as a placeholder for essential scripting logic. ```Django Template Language {% block main_scripts %} {% endblock %} ``` -------------------------------- ### Overriding ViewSet Operation Properties with @swagger_auto_schema (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst Illustrates how to use the '@swagger_auto_schema' decorator on a ViewSet's action method (e.g., 'partial_update') to override properties like 'operation_description' and document custom responses (e.g., 404). ```python from drf_yasg.utils import swagger_auto_schema @swagger_auto_schema(operation_description="partial_update description override", responses={404: 'slug not found'}) def partial_update(self, request, *args, **kwargs): """partial_update method docstring""" ... ``` -------------------------------- ### Fixing Base64 Fields in DRF-YASG with drf-extra-fields Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This Python class provides a workaround for an issue where `drf-yasg` incorrectly renders `drf-extra-fields` Base64 fields as read-only. By overriding the `swagger_schema_fields` in the `Meta` class, it explicitly sets `read_only` to `False`, ensuring the field is editable in the generated OpenAPI schema. It also includes a `get_file_extension` method for PDF validation using `PyPDF2`. ```python class PDFBase64FileField(Base64FileField): ALLOWED_TYPES = ['pdf'] class Meta: swagger_schema_fields = { 'type': 'string', 'title': 'File Content', 'description': 'Content of the file base64 encoded', 'read_only': False # <-- FIX } def get_file_extension(self, filename, decoded_file): try: PyPDF2.PdfFileReader(io.BytesIO(decoded_file)) except PyPDF2.utils.PdfReadError as e: logger.warning(e) else: return 'pdf' ``` -------------------------------- ### Defining a Django Model with JSONField in Python Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This snippet shows a basic Django model definition, Email, which includes an import for JSONField from django.contrib.postgres.fields. This model structure could be used as a basis for a DRF serializer, potentially demonstrating how drf-yasg handles complex field types. ```python from django.contrib.postgres.fields import JSONField class Email(models.Model): ``` -------------------------------- ### Adding Footer Markup in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This block is designated for custom HTML markup to be placed in the footer section of the documentation page, appearing after the main Swagger UI or ReDoc element. It's ideal for copyright information or navigation links. ```Django Template Language {% block footer %} {# -- Add any footer markup here (rendered AFTER the swagger-ui/redoc element) -- #} {% endblock %} ``` -------------------------------- ### Hiding Hostname in ReDoc Operation Definitions (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting, when `True`, prevents the protocol and hostname from being shown in the operation definition within ReDoc. It maps to the `hideHostname` attribute. ```python False ``` -------------------------------- ### Explicitly Defining SerializerMethodField Schema with swagger_serializer_method in Python Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This snippet provides an alternative to type hinting for SerializerMethodField by explicitly defining the field type using swagger_serializer_method. It demonstrates how to pass a serializers.Field subclass (e.g., serializers.FloatField) to ensure correct schema generation. ```python class SomeSerializer(serializers.Serializer): some_number = serializers.SerializerMethodField() @swagger_serializer_method(serializer_or_field=serializers.FloatField) def get_some_number(self, obj): return 1.0 ``` -------------------------------- ### Adding Extra Head Tags in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This block provides a placeholder for injecting additional HTML tags into the `` section of the document, excluding scripts and styles which have their own dedicated blocks. It's useful for meta tags or link rel attributes. ```Django Template Language {% block extra_head %} {# -- Add any extra HTML heads tags here - except scripts and styles -- #} {% endblock %} ``` -------------------------------- ### Customizing Favicon in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This block allows developers to replace or define the favicon for the documentation page. It's an optional block where a `` tag can be inserted. ```Django Template Language {% block favicon %} {# -- Maybe replace the favicon -- #} {% endblock %} ``` -------------------------------- ### Defining Page Title Block in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This block defines the `title` section of the HTML document, typically used within the `` tag. It allows overriding the page's title and dynamically inserts the `title` variable provided by the view context. ```Django Template Language {% block title %}{{ title }}{% endblock %} ``` -------------------------------- ### Configuring Default Model Expansion Depth in Swagger UI (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting controls the number of levels expanded by default when nested models are displayed in Swagger UI. A value of `3` means three levels will be expanded. It maps to the `defaultModelExpandDepth` parameter. ```python 3 ``` -------------------------------- ### Main Styles Block in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This block is intended for the primary CSS stylesheets of the documentation page. It serves as a placeholder where the main styling links or inline styles can be injected. ```Django Template Language {% block main_styles %} {% endblock %} ``` -------------------------------- ### Configuring Swagger UI Validator URL in Django Settings Source: https://github.com/axnsan12/drf-yasg/blob/master/README.rst This snippet demonstrates how to configure the `VALIDATOR_URL` within your Django project's `SWAGGER_SETTINGS`. This setting allows Swagger UI to validate your API schema against a local or custom validator instance, which is particularly useful for offline environments or specific validation requirements. ```python SWAGGER_SETTINGS = { ... 'VALIDATOR_URL': 'http://localhost:8189', ... } ``` -------------------------------- ### Adding Extra Scripts in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This block allows for the inclusion of additional JavaScript files or inline scripts. It's useful for custom functionalities, analytics, or third-party integrations specific to the project. ```Django Template Language {% block extra_scripts %} {# -- Add any additional scripts here -- #} {% endblock %} ``` -------------------------------- ### Detecting Mock Views for Swagger Introspection in Python Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/changelog.rst This Python snippet demonstrates how to check if a view instance is a 'fake' view used specifically for Swagger schema introspection. By accessing the 'swagger_fake_view' attribute, developers can conditionally modify behavior within view methods (e.g., 'get_serializer_class') to prevent unintended side effects during schema generation. ```Python getattr(self, 'swagger_fake_view', False) ``` -------------------------------- ### Controlling Operation ID Display in Swagger UI (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/settings.rst This setting controls whether the `operationId` is displayed in the operations list within Swagger UI. When `True`, the operation ID will be visible. It maps to the `displayOperationId` parameter. ```python True ``` -------------------------------- ### Defining Meta Class in DRF Serializer for Schema Options in Python Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This snippet illustrates the basic structure for defining a nested Meta class within a Django REST Framework Serializer. The Meta class is used to configure serializer-wide or field-specific options for schema generation, such as ref_name or swagger_schema_fields. ```python class WhateverSerializer(Serializer): ... class Meta: ... options here ... ``` -------------------------------- ### Adding Extra Styles in Django Template Source: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html This block allows for the inclusion of additional CSS stylesheets beyond the main styles. It's useful for custom styling or overrides specific to the project's needs. ```Django Template Language {% block extra_styles %} {# -- Add any additional CSS scripts here -- #} {% endblock %} ``` -------------------------------- ### Detecting drf-yasg Introspection in Django REST Framework Serializer Class Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/openapi.rst This Python snippet demonstrates how to use the 'swagger_fake_view' marker to detect if the current view instance is a 'fake' view created by drf-yasg for schema introspection. This allows developers to provide a simplified or fixed serializer (e.g., TodoTreeSerializer) specifically for schema generation, preventing complex or stateful logic in get_serializer_class from being executed during introspection, which could otherwise lead to errors or unexpected behavior. ```python def get_serializer_class(self): if getattr(self, 'swagger_fake_view', False): return TodoTreeSerializer raise NotImplementedError("must not call this") ``` -------------------------------- ### Excluding Endpoints from Swagger Schema in drf-yasg (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst Demonstrates how to prevent views or specific methods from appearing in the generated Swagger documentation. A class-level 'swagger_schema = None' excludes all methods of a class, while '@swagger_auto_schema(auto_schema=None)' on a specific method excludes only that operation. ```python 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 ``` -------------------------------- ### Defining Custom JSONField Schema for Email Messages (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This snippet demonstrates how to create a custom JSONField subclass (EmailMessageField) in Django REST Framework with drf-yasg to define a specific OpenAPI schema for a JSON object containing 'subject' and 'body' properties. It also shows how to integrate this custom field into a ModelSerializer to ensure the generated schema accurately reflects the expected JSON structure. ```Python class EmailMessageField(serializers.JSONField): class Meta: swagger_schema_fields = { "type": openapi.TYPE_OBJECT, "title": "Email", "properties": { "subject": openapi.Schema( title="Email subject", type=openapi.TYPE_STRING, ), "body": openapi.Schema( title="Email body", type=openapi.TYPE_STRING, ), }, "required": ["subject", "body"], } class EmailSerializer(ModelSerializer): class Meta: model = Email fields = "__all__" message = EmailMessageField() ``` -------------------------------- ### Removing Schema Titles in drf-yasg OpenAPI Generation (Python) Source: https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst This snippet defines a custom `FieldInspector` (`NoSchemaTitleInspector`) and an `AutoSchema` (`NoTitleAutoSchema`) to remove the `title` attribute from all generated OpenAPI Schema objects. It correctly handles schema references by resolving them before modification. This is useful for scenarios where default schema titles are not desired or conflict with specific OpenAPI requirements. It requires `drf_yasg` and `Django REST Framework`. ```python from drf_yasg.inspectors import FieldInspector class NoSchemaTitleInspector(FieldInspector): def process_result(self, result, method_name, obj, **kwargs): # remove the `title` attribute of all Schema objects if isinstance(result, openapi.Schema.OR_REF): # traverse any references and alter the Schema object in place schema = openapi.resolve_ref(result, self.components) schema.pop('title', None) # no ``return schema`` here, because it would mean we always generate # an inline `object` instead of a definition reference # return back the same object that we got - i.e. a reference if we got a reference return result class NoTitleAutoSchema(SwaggerAutoSchema): field_inspectors = [NoSchemaTitleInspector] + swagger_settings.DEFAULT_FIELD_INSPECTORS class ArticleViewSet(viewsets.ModelViewSet): swagger_schema = NoTitleAutoSchema ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.