djangodjango-rest-frameworkswaggerhttp-accept-languagedrf-spectacular

How to add global header parameter to all url paths in drf_spectacular?


I'm using drf_spectacular to be able to use swagger and it's working fine. I define the required parameters for my API views (whether in the path or in the header) like this:

@extend_schema(
    OpenApiParameter(
            name='accept-language',
            type=str,
            location=OpenApiParameter.HEADER,
            description="fa or en. The default value is en"
    ),
)

but I don't want to add these lines of code to all of my API views. Is there an easy way to do this? (Something like defining these lines of code in SPECTACULAR_SETTINGS)

I already found an APPEND_COMPONENTS option in drf_spectacular's documentation but I'm not familiar with it.


Solution

  • You can create a custom schema class from drf_spectacular.openapi.AutoSchema and override the get_override_parameters(...) method as

    from drf_spectacular.openapi import AutoSchema
    
    from drf_spectacular.utils import OpenApiParameter
    
    
    class CustomAutoSchema(AutoSchema):
        global_params = [
            OpenApiParameter(
                name="accept-language",
                type=str,
                location=OpenApiParameter.HEADER,
                description="`fa` or `en`. The default value is en",
            )
        ]
    
        def get_override_parameters(self):
            params = super().get_override_parameters()
            return params + self.global_params
    

    and then attach this CustomAutoSchema class in your DEFAULT_SCHEMA_CLASS setting

    REST_FRAMEWORK = {
        # YOUR SETTINGS
        "DEFAULT_SCHEMA_CLASS": "path.to.your.custom.class.CustomAutoSchema",
    }