### Local Development and Testing Setup Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/contributing.md This command sequence sets up a local development environment for drf-spectacular. It includes forking the repository, cloning it, creating a virtual environment, installing dependencies, and running the test suite which also performs linting. ```bash $ # fork the repo on github $ git clone https://github.com/YOURGITHUBNAME/drf-spectacular $ cd drf-spectacular $ python -m venv venv $ source venv/bin/activate (venv) $ pip install -r requirements.txt (venv) $ ./runtests.py # runs tests (pytest) & linting (isort, flake8, mypy) ``` -------------------------------- ### Install drf-spectacular Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Install the drf-spectacular package using pip. ```bash pip install drf-spectacular ``` -------------------------------- ### Install Testing Requirements Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Install the necessary testing dependencies using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Testing Requirements Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Install project dependencies for testing using pip and a requirements file. This is a standard step before running tests. ```bash $ pip install -r requirements.txt ``` -------------------------------- ### Install drf-spectacular with Sidecar Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Install drf-spectacular with the 'sidecar' extra to include static files for Swagger UI and Redoc locally. This is useful for environments without internet access. ```bash $ pip install drf-spectacular[sidecar] ``` -------------------------------- ### Install drf-spectacular Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Install the drf-spectacular package using pip. This is the first step to integrate OpenAPI schema generation into your Django REST Framework project. ```bash $ pip install drf-spectacular ``` -------------------------------- ### Generate schema with CLI Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Use the manage.py spectacular command to generate the OpenAPI schema file. This example generates a YAML file and includes color output. ```bash $ ./manage.py spectacular --color --file schema.yml ``` -------------------------------- ### Serve In-Memory Generated Files with BinaryRenderer Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/faq.md To serve binary files generated in-memory, create a custom `BinaryRenderer` and use `responses=bytes` in `@extend_schema`. This example demonstrates setting the `Content-Disposition` header for file downloads. ```python from django.http import HttpResponse from rest_framework.renderers import BaseRenderer class BinaryRenderer(BaseRenderer): media_type = "application/octet-stream" format = "bin" class FileViewSet(RetrieveModelMixin, GenericViewSet): ... renderer_classes = [BinaryRenderer] @extend_schema(responses=bytes) def retrieve(self, request, *args, **kwargs): export_data = b"..." return HttpResponse( export_data, content_type=BinaryRenderer.media_type, headers={ "Content-Disposition": "attachment; filename=out.bin", }, ) ``` -------------------------------- ### Run Tests with Tox Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Utilize the tox tool to run tests across multiple Python and Django versions. Ensure tox is installed globally first. ```bash tox ``` -------------------------------- ### Extend Schema with Parameters and Examples Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Use the extend_schema decorator to add custom parameters, examples, and override schema details like description, auth, and operation ID. This is useful for fine-tuning the OpenAPI schema generated for your views. ```python @extend_schema( # extra parameters added to the schema parameters=[ OpenApiParameter(name='artist', description='Filter by artist', required=False, type=str), OpenApiParameter( name='release', type=OpenApiTypes.DATE, location=OpenApiParameter.QUERY, description='Filter by release date', examples=[ OpenApiExample( 'Example 1', summary='short optional summary', description='longer description', value='1993-08-23' ), ... ], ), ], # override default docstring extraction description='More descriptive text', # provide Authentication class that deviates from the views default auth=None, # change the auto-generated operation name operation_id=None, # or even completely override what AutoSchema would generate. Provide raw Open API spec as Dict. operation=None, # attach request/response examples to the operation. examples=[ OpenApiExample( 'Example 1', description='longer description', value=... ), ... ], ) def list(self, request): # your non-standard behaviour return super().list(request) ``` -------------------------------- ### Run Tests with Tox Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Utilize the tox tool to run tests across multiple Python and Django versions. Ensure tox is installed globally before running. ```bash $ tox ``` -------------------------------- ### Configure Spectacular Settings for Sidecar Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Configure SPECTACULAR_SETTINGS to use the 'SIDECAR' shorthand for SWAGGER_UI_DIST and REDOC_DIST. This points drf-spectacular to use the locally installed static files from the sidecar package. ```python SPECTACULAR_SETTINGS = { 'SWAGGER_UI_DIST': 'SIDECAR', 'SWAGGER_UI_FAVICON_HREF': 'SIDECAR', 'REDOC_DIST': 'SIDECAR', # OTHER SETTINGS } ``` -------------------------------- ### DRF Spectacular Elements View Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/blueprints.md This Python view class integrates with drf-spectacular to serve schema documentation via the Elements tool. It requires specific settings for renderers, permissions, and authentication. The `get` method prepares data for the HTML template, including schema URL and distribution links for Elements. ```python from rest_framework.renderers import TemplateHTMLRenderer from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.views import APIView from drf_spectacular.plumbing import get_relative_url, set_query_parameters from drf_spectacular.settings import spectacular_settings from drf_spectacular.utils import extend_schema from drf_spectacular.views import AUTHENTICATION_CLASSES class SpectacularElementsView(APIView): renderer_classes = [TemplateHTMLRenderer] permission_classes = spectacular_settings.SERVE_PERMISSIONS authentication_classes = AUTHENTICATION_CLASSES url_name = 'schema' url = None template_name = 'elements.html' title = spectacular_settings.TITLE @extend_schema(exclude=True) def get(self, request, *args, **kwargs): return Response( data={ 'title': self.title, 'js_dist': 'https://unpkg.com/@stoplight/elements/web-components.min.js', 'css_dist': 'https://unpkg.com/@stoplight/elements/styles.min.css', 'schema_url': self._get_schema_url(request), }, template_name=self.template_name ) def _get_schema_url(self, request): schema_url = self.url or get_relative_url(reverse(self.url_name, request=request)) return set_query_parameters( url=schema_url, lang=request.GET.get('lang'), version=request.GET.get('version') ) ``` -------------------------------- ### Fix django-oscar-api Category List View with OpenApiParameter for drf-spectacular Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/blueprints.md This example shows how to fix the oscarapi.views.product.CategoryList view by adding an OpenApiParameter for 'breadcrumbs' to the GET method using extend_schema. It uses OpenApiViewExtension. ```python from drf_spectacular.extensions import OpenApiViewExtension from drf_spectacular.plumbing import build_basic_type from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import OpenApiParameter, extend_schema class Fix5(OpenApiViewExtension): target_class = 'oscarapi.views.product.CategoryList' def view_replacement(self): class Fixed(self.target_class): @extend_schema(parameters=[ OpenApiParameter(name='breadcrumbs', type=OpenApiTypes.STR, location=OpenApiParameter.PATH) ]) def get(self, request, *args, **kwargs): pass return Fixed ``` -------------------------------- ### Initialize Redoc with Schema and Settings Source: https://github.com/tfranzel/drf-spectacular/blob/master/drf_spectacular/templates/drf_spectacular/redoc.html This JavaScript code initializes Redoc by passing the schema URL and settings object to the Redoc.init function. Ensure the 'redoc-container' element exists in the HTML. ```javascript const redocSettings = {{ settings|safe }}; Redoc.init("{{ schema_url }}", redocSettings, document.getElementById('redoc-container')) ``` -------------------------------- ### Recommended Client Generation Command Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/client_generation.md Use this command for generating clients with CI to catch potential problems early. It validates the schema and fails on warnings. ```bash ./manage.py spectacular --file schema.yaml --validate --fail-on-warn ``` -------------------------------- ### Exclude Fields and Add Examples with @extend_schema_serializer Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/customization.md Use this decorator to exclude specific fields from the schema or to attach request/response examples. It can also override list detection with `many=False` for envelope serializers. ```python from drf_spectacular.utils import extend_schema_serializer, OpenApiExample from rest_framework import serializers # Assuming SongSerializer and Album models are defined elsewhere @extend_schema_serializer( exclude_fields=('single',), # schema ignore these fields examples = [ OpenApiExample( 'Valid example 1', summary='short summary', description='longer description', value={ 'songs': {'top10': True}, 'single': {'top10': True} }, # request_only=True, # signal that example only applies to requests # response_only=True, # signal that example only applies to responses ), ] ) class AlbumSerializer(serializers.ModelSerializer): songs = SongSerializer(many=True) single = SongSerializer(read_only=True) class Meta: fields = '__all__' model = Album ``` -------------------------------- ### Configure Redoc for CSP with SIDECAR or CDN Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/faq.md Adjust CSP settings for Redoc to accommodate SIDECAR or CDN assets. Covers required directives for both options. ```python # Option: SIDECAR SPECTACULAR_SETTINGS = { ... 'REDOC_DIST': 'SIDECAR', } # Option: CDN CSP_DEFAULT_SRC = ("'self'", "cdn.jsdelivr.net") # required for both CDN and SIDECAR CSP_WORKER_SRC = ("'self'", "blob:") CSP_IMG_SRC = ("'self'", "data:", "cdn.redoc.ly") CSP_STYLE_SRC = ("'self'", "'unsafe-inline'", "fonts.googleapis.com") CSP_FONT_SRC = ("'self'", "fonts.gstatic.com") ``` -------------------------------- ### Fix django-oscar-api Product Price View for drf-spectacular Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/blueprints.md This example fixes the oscarapi.views.product.ProductPrice view by assigning PriceSerializer to serializer_class. OpenApiViewExtension is used for this purpose. ```python from drf_spectacular.extensions import OpenApiViewExtension class Fix3(OpenApiViewExtension): target_class = 'oscarapi.views.product.ProductPrice' def view_replacement(self): from oscarapi.serializers.checkout import PriceSerializer class Fixed(self.target_class): serializer_class = PriceSerializer return Fixed ``` -------------------------------- ### Configure Swagger UI for CSP with SIDECAR or CDN Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/faq.md Adapt CSP settings to allow Swagger UI assets when using the SIDECAR option or CDN. Includes options for both. ```python # Option: SIDECAR SPECTACULAR_SETTINGS = { ... 'SWAGGER_UI_DIST': 'SIDECAR', 'SWAGGER_UI_FAVICON_HREF': 'SIDECAR', } CSP_DEFAULT_SRC = ("'self'", "'unsafe-inline'") CSP_IMG_SRC = ("'self'", "data:") # Option: CDN CSP_DEFAULT_SRC = ("'self'", "'unsafe-inline'", "cdn.jsdelivr.net") CSP_IMG_SRC = ("'self'", "data:", "cdn.jsdelivr.net") ``` -------------------------------- ### Fix django-oscar-api Basket Serializer with SerializerMethodField for drf-spectacular Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/blueprints.md This example fixes the oscarapi.serializers.basket.BasketSerializer by adding a 'is_tax_known' SerializerMethodField. It uses OpenApiSerializerExtension to map the modified serializer. ```python from rest_framework import serializers from drf_spectacular.extensions import OpenApiSerializerExtension class Fix9(OpenApiSerializerExtension): target_class = 'oscarapi.serializers.basket.BasketSerializer' def map_serializer(self, auto_schema, direction): class Fixed(self.target_class): is_tax_known = serializers.SerializerMethodField() def get_is_tax_known(self) -> bool: pass return auto_schema._map_serializer(Fixed, direction) ``` -------------------------------- ### Generate Schema with CLI and Serve with Swagger UI Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Generate your API schema using the CLI and then serve it using Swagger UI via Docker. The `--validate` flag can be added for schema validation. ```bash $ ./manage.py spectacular --color --file schema.yml $ docker run -p 8080:8080 -e SWAGGER_JSON=/schema.yml -v ${PWD}/schema.yml:/schema.yml swaggerapi/swagger-ui ``` -------------------------------- ### Map django-oscar-api Category Field to String for drf-spectacular Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/blueprints.md This example shows how to map the oscarapi.serializers.fields.CategoryField to a basic string type using build_basic_type. It utilizes OpenApiSerializerFieldExtension. ```python from drf_spectacular.extensions import OpenApiSerializerFieldExtension from drf_spectacular.plumbing import build_basic_type from drf_spectacular.types import OpenApiTypes class Fix7(OpenApiSerializerFieldExtension): target_class = 'oscarapi.serializers.fields.CategoryField' def map_serializer_field(self, auto_schema, direction): return build_basic_type(OpenApiTypes.STR) ``` -------------------------------- ### Configure Spectacular Settings Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Optionally configure SPECTACULAR_SETTINGS in settings.py to customize API metadata like title, description, and version. SERVE_INCLUDE_SCHEMA can be set to False to exclude the schema from being served directly. ```python SPECTACULAR_SETTINGS = { 'TITLE': 'Your Project API', 'DESCRIPTION': 'Your project description', 'VERSION': '1.0.0', 'SERVE_INCLUDE_SCHEMA': False, # OTHER SETTINGS } ``` -------------------------------- ### Fix django-oscar-api API Root View for drf-spectacular Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/blueprints.md This example demonstrates fixing the oscarapi.views.root.api_root view to correctly document its responses using OpenApiTypes.OBJECT. It utilizes OpenApiViewExtension for the modification. ```python from drf_spectacular.extensions import OpenApiViewExtension from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import extend_schema class Fix1(OpenApiViewExtension): target_class = 'oscarapi.views.root.api_root' def view_replacement(self): return extend_schema(responses=OpenApiTypes.OBJECT)(self.target_class) ``` -------------------------------- ### Run Tests with runtests.py Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Execute the test suite using the provided runtests.py script. ```bash ./runtests.py ``` -------------------------------- ### Extend Schema with @extend_schema Decorator Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Customize API schema generation for viewset methods using the `extend_schema` decorator. This allows for detailed specification of request/response serializers, parameters, and examples. ```python from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiExample from drf_spectacular.types import OpenApiTypes class AlbumViewset(viewset.ModelViewset): serializer_class = AlbumSerializer @extend_schema( request=AlbumCreationSerializer, responses={201: AlbumSerializer}, ) def create(self, request): # your non-standard behaviour return super().create(request) @extend_schema( # extra parameters added to the schema parameters=[ OpenApiParameter(name='artist', description='Filter by artist', required=False, type=str), OpenApiParameter( name='release', type=OpenApiTypes.DATE, location=OpenApiParameter.QUERY, description='Filter by release date', examples=[ OpenApiExample( 'Example 1', summary='short optional summary', description='longer description', value='1993-08-23' ), ... ], ), ], # override default docstring extraction description='More descriptive text', # provide Authentication class that deviates from the views default auth=None, # change the auto-generated operation name operation_id=None, # or even completely override what AutoSchema would generate. Provide raw Open API spec as Dict. operation=None, # attach request/response examples to the operation. examples=[ OpenApiExample( 'Example 1', description='longer description', value=... ), ... ], ) def list(self, request): # your non-standard behaviour return super().list(request) @extend_schema( request=AlbumLikeSerializer, responses={204: None}, methods=["POST"] ) @extend_schema(description='Override a specific method', methods=["GET"]) @action(detail=True, methods=['post', 'get']) def set_password(self, request, pk=None): # your action behaviour ... ``` -------------------------------- ### Serve schema with Swagger UI Docker container Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Run a Docker container for Swagger UI, mapping a local schema file to be served. The SWAGGER_JSON environment variable points to the schema file. ```bash $ docker run -p 8080:8080 -e SWAGGER_JSON=/schema.yml -v ${PWD}/schema.yml:/schema.yml swaggerapi/swagger-ui ``` -------------------------------- ### Override Specific Methods with extend_schema and action Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Customize specific HTTP methods (POST, GET) for an action using multiple extend_schema decorators and the action decorator. This allows for method-specific request/response schemas and descriptions. ```python @extend_schema( request=AlbumLikeSerializer, responses={204: None}, methods=["POST"] ) @extend_schema(description='Override a specific method', methods=["GET"]) @action(detail=True, methods=['post', 'get']) def set_password(self, request, pk=None): # your action behaviour ... ``` -------------------------------- ### list method customization Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Demonstrates how to use the extend_schema decorator to add custom parameters, descriptions, and authentication overrides for the list method. ```APIDOC ## GET /list ### Description Customizes the schema for the list method, allowing for filtering by artist and release date, and overriding the default description. ### Method GET ### Endpoint /list ### Parameters #### Query Parameters - **artist** (string) - Optional - Filter by artist - **release** (date) - Optional - Filter by release date ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Multiple SpectacularAPIView with Custom Settings Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/faq.md Define a base schema in settings.py and provide scoped overrides using the `custom_settings` argument for different API schemas. Note that this is not thread-safe and certain settings cannot be overridden this way. ```python urlpatterns = [ path('api/schema/', SpectacularAPIView.as_view(), path('api/schema-custom/', SpectacularAPIView.as_view( custom_settings={ 'TITLE': 'your custom title', 'SCHEMA_PATH_PREFIX': 'your custom regex', ... } ), name='schema-custom'), ] ``` -------------------------------- ### Configure Django settings for sidecar UI Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Add drf_spectacular_sidecar to INSTALLED_APPS and configure SPECTACULAR_SETTINGS to use the sidecar for UI assets. ```python INSTALLED_APPS = [ # ALL YOUR APPS 'drf_spectacular', 'drf_spectacular_sidecar', # required for Django collectstatic discovery ] SPECTACULAR_SETTINGS = { 'SWAGGER_UI_DIST': 'SIDECAR', # shorthand to use the sidecar instead 'SWAGGER_UI_FAVICON_HREF': 'SIDECAR', 'REDOC_DIST': 'SIDECAR', # OTHER SETTINGS } ``` -------------------------------- ### Run Tests with runtests.py Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Execute the test suite using the provided runtests.py script. This is a common way to run tests in Django projects. ```bash $ ./runtests.py ``` -------------------------------- ### Import Schema Extensions in Django Apps Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/faq.md Import schema extensions in the `ready()` method of your Django app configuration for robust detection. This ensures extensions are loaded after the environment is set up. ```python # your_main_app_name/apps.py class YourMainAppNameConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "your_main_app_name" def ready(self): import your_main_app_name.schema # noqa: E402 ``` -------------------------------- ### Configure INSTALLED_APPS for Sidecar Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md When using the sidecar, ensure 'drf_spectacular_sidecar' is added to INSTALLED_APPS for Django's collectstatic to discover the static files. ```python INSTALLED_APPS = [ # ALL YOUR APPS 'drf_spectacular', 'drf_spectacular_sidecar', # required for Django collectstatic discovery ] ``` -------------------------------- ### Component Settings for Client Generation Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/client_generation.md These settings control how components are split and handled, particularly for request/response differences and read-only fields, to improve client compatibility. ```python 'COMPONENT_SPLIT_REQUEST': False, ``` ```python 'COMPONENT_NO_READ_ONLY_REQUIRED': False, ``` ```python 'COMPONENT_SPLIT_PATCH': True, ``` -------------------------------- ### Schema and UI Endpoints Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Provides the necessary URL patterns to serve the OpenAPI schema and its associated UI documentation (Swagger UI and Redoc). ```APIDOC ## GET api/schema/ ### Description Serves the OpenAPI schema for the project. ### Method GET ### Endpoint /api/schema/ ### Response #### Success Response (200) - **schema** (object) - The OpenAPI schema definition. ### Response Example { "example": "{\"openapi\": \"3.0.0\", \"info\": {\"title\": \"Your Project API\", \"version\": \"1.0.0\"}, ...}" } ## GET api/schema/swagger-ui/ ### Description Serves the Swagger UI interface for visualizing the OpenAPI schema. ### Method GET ### Endpoint /api/schema/swagger-ui/ ## GET api/schema/redoc/ ### Description Serves the Redoc interface for visualizing the OpenAPI schema. ### Method GET ### Endpoint /api/schema/redoc/ ``` -------------------------------- ### Equivalent @extend_schema_view Usage Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/customization.md Demonstrates an alternative way to apply `@extend_schema` to a viewset's method using `@extend_schema_view`, which can be more concise for annotating multiple methods or default implementations. ```python @extend_schema_view( list=extend_schema(description='text') ) class XViewset(mixins.ListModelMixin, viewsets.GenericViewSet): ... ``` -------------------------------- ### Configure API Key Security Scheme Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/blueprints.md Manually add an API key security scheme to SPECTACULAR_SETTINGS when drf-spectacular cannot auto-detect it. This configuration appends the 'ApiKeyAuth' scheme to all endpoints. ```python SPECTACULAR_SETTINGS = { "APPEND_COMPONENTS": { "securitySchemes": { "ApiKeyAuth": { "type": "apiKey", "in": "header", "name": "Authorization" } } }, "SECURITY": [{"ApiKeyAuth": [], }], ... ``` -------------------------------- ### Add drf-spectacular to INSTALLED_APPS Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/readme.md Add 'drf_spectacular' to your Django project's INSTALLED_APPS in settings.py. This enables drf-spectacular to be recognized by Django. ```python INSTALLED_APPS = [ # ALL YOUR APPS 'drf_spectacular', ] ``` -------------------------------- ### Configure SwaggerUI Settings in SPECTACULAR_SETTINGS Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/settings.md Pass basic SwaggerUI configuration parameters directly within your SPECTACULAR_SETTINGS. For advanced customization like CSS or JS functions, override the SwaggerUI template. ```python SPECTACULAR_SETTINGS = { ... # available SwaggerUI configuration parameters # https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ "SWAGGER_UI_SETTINGS": { "deepLinking": True, "persistAuthorization": True, "displayOperationId": True, ... }, # available SwaggerUI versions: https://github.com/swagger-api/swagger-ui/releases "SWAGGER_UI_DIST": "https://cdn.jsdelivr.net/npm/swagger-ui-dist@latest", # default "SWAGGER_UI_FAVICON_HREF": settings.STATIC_URL + "your_company_favicon.png", # default is swagger favicon ... } ``` -------------------------------- ### Docstring Parsing for Operation Summary and Description Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/drf_yasg.md drf-yasg splits the first line of a docstring for the summary and uses the rest for the description. drf-spectacular uses the entire docstring as the description. Use the `summary` and `description` arguments of `@extend_schema` to achieve similar results. ```python class UserViewSet(ViewSet): def list(self, request): """ List all the users. Return a list of all usernames in the system. """ ... ``` ```python class UserViewSet(ViewSet): @extend_schema( summary="List all the users.", description="Return a list of all usernames in the system.", ) def list(self, request): ... ``` ```python class UserViewSet(ViewSet): @extend_schema(summary="List all the users.") def list(self, request): """Return a list of all usernames in the system.""" ... ``` -------------------------------- ### set_password action customization Source: https://github.com/tfranzel/drf-spectacular/blob/master/README.rst Shows how to customize the schema for the set_password action, specifying request body serializer, response codes, and overriding descriptions for different HTTP methods. ```APIDOC ## POST /set_password ### Description Customizes the schema for the set_password action. Allows POST requests with a specific serializer and expects a 204 No Content response. Also overrides the description for GET requests. ### Method POST ### Endpoint /set_password ### Parameters #### Path Parameters - **pk** (string) - Required - The primary key of the object. ### Request Body - **AlbumLikeSerializer** - Required - Serializer for the request body. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (204) None #### Response Example ```json { "example": "response body" } ``` ## GET /set_password ### Description Overrides the default description for the GET method of the set_password action. ### Method GET ### Endpoint /set_password ### Parameters #### Path Parameters - **pk** (string) - Required - The primary key of the object. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Annotate Default Viewset Methods with @extend_schema_view Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/customization.md When annotating methods provided by base classes, use `@extend_schema_view` to apply `@extend_schema` to specific methods like `list`. This is equivalent to decorating the method directly. ```python class XViewset(mixins.ListModelMixin, viewsets.GenericViewSet): @extend_schema(description='text') def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) ``` -------------------------------- ### Replace Views with OpenApiViewExtension Source: https://github.com/tfranzel/drf-spectacular/blob/master/docs/customization.md Use `OpenApiViewExtension` to augment or replace views during schema generation, particularly for libraries using `@api_view` or `APIView`. Implement `view_replacement` to provide a modified or new view class. ```python from drf_spectacular.extensions import OpenApiViewExtension from oscar.apps.address.models import UserAddress # Assuming AvailabilitySerializer is defined elsewhere class Fix4(OpenApiViewExtension): target_class = 'oscarapi.views.checkout.UserAddressDetail' def view_replacement(self): class Fixed(self.target_class): # Example 1: missing or dynamic information queryset = UserAddress.objects.none() # Example 2: another example for a common issue serializer_class = AvailabilitySerializer return Fixed ```