I.Jokhadze
I.Jokhadze

Reputation: 477

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?

Upvotes: 4

Views: 2388

Answers (2)

Tried the answer provided by Moheb, and it worked. But at a later attempt, swagger UI showed the input field for the variable, but I was not able see the values in request.headers. After much exploration I realized the following: while defining a local/custom header parameter as provided in the answer, ensure that the variable name doesnot contain any underscore. As an example, the below code will not pass the value of the parameter since its name is local_first, instead of localfirst

 header_param = openapi.Parameter('local_first',openapi.IN_HEADER,description="local header param", type=openapi.IN_HEADER)

So, the correct code that worked for me is

 header_param = openapi.Parameter('localfirst',openapi.IN_HEADER,description="local header param", type=openapi.IN_HEADER)

Upvotes: 0

Moheb
Moheb

Reputation: 138

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.

Upvotes: 5

Related Questions