Search code examples
djangodjango-rest-frameworkdrf-yasg

Django drf-yasg swagger required header LOCALE parameter for every route


Is it possible to make header locale parameter required for every URL in application. Can i achieve it to set it up in global configuration or in every view method and if yes how can i do this?


Solution

  • You have not given any details on how your view looks so i'll assume it is function based not class based but this solution can easily be implemented on cbv.

    Making header as a part of swagger can be achieved by this:

    # making a header parameter
    
    from drf_yasg import openapi
    
    header_param = openapi.Parameter('local',openapi.IN_HEADER,description="local header param", type=openapi.IN_HEADER)
    
    # calling it on view
    
    @swagger_auto_schema(manual_parameters=[header_param])
    @api_view(['GET', 'PUT', 'POST'])
    def test_view(request, pk):
    

    As you want it for every view, one solution is create a utils folder for making helper methods. create a helper method like:

    # utils.py
    from drf_yasg import openapi
    
    def get_header_params(self):
        header_param = openapi.Parameter('local',openapi.IN_HEADER,description="local header param", type=openapi.IN_HEADER)
     
        return [header_param]
    

    with this you can call this method in your every view like:

    # views.py
    
    from utils.get_header_param
    
    @swagger_auto_schema(manual_parameters=get_header_param())
    @api_view(['GET', 'PUT', 'POST'])
    def test_view(request, pk):
        # your code
    
    @swagger_auto_schema(manual_parameters=get_header_param())
    @api_view(['GET', 'PUT', 'POST'])
    def test_view_2(request, pk):
        # your code
    
    

    for further help you can always look through the actual documentation: https://drf-yasg.readthedocs.io/en/stable/custom_spec.html#the-swagger-auto-schema-decorator

    If you've started this project then i'll suggest to use drf-spectacular instead of this even yasg and django also recommends it for future projects.