django-rest-swagger icon indicating copy to clipboard operation
django-rest-swagger copied to clipboard

Django rest swagger post parameter

Open JenishGnanasicamani opened this issue 7 years ago • 19 comments

I have integrated swagger with django rest framework, but the swagger docs does not create a input box to post data for post request.

Here is my view class snippet, class TeamViewList(APIView, BaseView): """ Class based view to handle all operations related to Team Model """ logger = logging.getLogger(name)

def get_serializer(self): return serializers.TeamSerializer

def post(self, request): """ To create a new team """ try:`

Url Mapping: urlpatterns = [ url(r'^role/$', rest_views.UserTeamRoleView.as_view(), name='user_team_role'), url(r'^teams/$', rest_views.TeamViewList.as_view(), name='team_list'), url(r'^teams/(?P<name>[_a-zA-Z0-9\-]+)$', rest_views.TeamViewDetail.as_view(), name='team_detail'),

Generated Docs screenshot 3

There is no way to pass the input parameters for the post request.

JenishGnanasicamani avatar Mar 22 '17 06:03 JenishGnanasicamani

@marcgibbons Could you please let me know what i am missing?

JenishGnanasicamani avatar Mar 23 '17 11:03 JenishGnanasicamani

Join the question. Need a way to document POST/GET parameters

skkap avatar Apr 26 '17 07:04 skkap

@JenishGnanasicamani

Short anwser: you need to inhehit from GenericAPIView:

-class TeamViewList(APIView, BaseView):
+class TeamViewList(GenericAPIView):
     """

Long anwser: django-rest-swagger uses rest_framework.schemas.SchemaGenerator to generate the schema and SchemaGenerator uses get_serializer_fields to get the serializer information of a view. get_serializer_fields checks if a view has a get_serializer method to generate the form. GenericAPIView provides the get_serializer so inheriting from it is enough.

marsam avatar May 03 '17 01:05 marsam

@marsam what if FBV with the decorator @api_view is used?

francbartoli avatar May 10 '17 09:05 francbartoli

@marsam Is there way to just display the input payload without serializer in the swagger docs?

JenishGnanasicamani avatar May 10 '17 12:05 JenishGnanasicamani

In my case I need just "data" field in POST requests. Views decorated as api_vew() and only one way how can I do it - add named group to URL dispatcher. In this case I will have not so elegant view of URL: url(r'^services/restart/(?P[\w-]+)$', views.service_restart, name='service_restart').

in v1 I can use YAML docstring, but I need to find solution for v2. Can someone help with this?

v-avdeev avatar May 18 '17 14:05 v-avdeev

@JenishGnanasicamani Found one solution: class Book_list(generics.ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializer

urlpatterns = [ url(r'^$', schema_view), url(r'books/$', views.Book_list.as_view(), name='Book_list'), ]

class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'title', 'author', 'publish_date', 'publisher', 'summary', 'price', 'link', 'image')

As result: 2017-05-19_0940

In my case, I still don't know how to setup only POST request for this view. Any ideas?

v-avdeev avatar May 19 '17 06:05 v-avdeev

Found solution for my case: class Book_list(generics.ListCreateAPIView): allowed_methods = ["POST"] queryset = Book.objects.all() serializer_class = BookSerializer

v-avdeev avatar May 22 '17 07:05 v-avdeev

@vladmir Is there a way to just display the input payload without serializer in the swagger docs?

JenishGnanasicamani avatar May 24 '17 06:05 JenishGnanasicamani

in settings.py add:

SWAGGER_SETTINGS = { 'JSON_EDITOR': True, }

image

likaiguo avatar Jun 11 '17 11:06 likaiguo

Is there a solution for the Function Based View ? I found solutions only for CBV

sudaraka94 avatar Jul 26 '17 06:07 sudaraka94

@likaiguo I am not able to get the data entry filed like your example here. I am using 'ViewSet' class for the views class to inherit from. And I set the Settings.py file as you have mentioned here. Please need help its Urgent

KumarGeoSpark avatar Jul 27 '17 12:07 KumarGeoSpark

Hi all, I have recently integrated Django Rest Swagger 2 into an existing project, I faced alot of issues, and resolved them by finding solutions at different forums. Now I have documented all the required steps here: https://github.com/m-haziq/django-rest-swagger-docs with all possible issues I could face and their solutions.

m-haziq avatar Oct 12 '17 15:10 m-haziq

Hello, @m-haziq

djangorestframework==3.6.4 django-rest-swagger==2.1.2

I have used your documentation but still I'm not able to pass parameters in POST and GET methods.

Here is my view:

class PostAddActivitySet(APIView): permission_classes = (AllowAny,)

def get(self, request, format=None):
    """
    Here we will get company and team id according to the team name.

    """
    team_name = request.GET.get('team_name')
    if team_name:
        team = Team.objects.get(team_name= team_name)
        team_list =[]
        team_list.append({ 'company_uid':team.company_id, 'team_uid':team.uid})
        return Response({
                'message': "Company and team id.",
                'status':status.HTTP_200_OK,
                'team_list': team_list,
                })
    return Response({
                'message': "Teams not found.",
                'status':status.HTTP_400_BAD_REQUEST,
                })

 def post(self, request, format=None):
     auth_obj = Authentication.objects.all()

     client = upwork.Client(settings.UPWORK_PUBLIC_KEY, settings.UPWORK_SECRET_KEY, auth_obj[0].oauth_access_token,auth_obj[0].oauth_access_token_secret)
    if client:
        code = request.POST.get('activity_code')
        desc = request.POST.get('activity_description')
        company_uid = request.POST.get('company_uid')
        team_uid = request.POST.get('team_uid')
        """
        TODO: all_in_company= 0,1: to assign all engagements then put 1 otherwise 0
        """
        client.task.post_team_task(company_uid, team_uid, code, desc, '', all_in_company=1)
        return Response({
                'status': status.HTTP_200_OK,
                'message': "Activity successfully created."
            })
    return Response({
            'status': status.HTTP_403_FORBIDDEN,
            'message': "Token combination does not exist or is not enabled." 
        })

GyanP avatar Nov 16 '17 07:11 GyanP

Hi @GyanP , there are two possibilities which are causing you issue: 1- Your versions do not match to the versions defined in my documentation, the documentation asks you to have djangorestframework==3.5.3 and django-rest-swagger==2.1.1. 2- Inside your code, I do not see serializer anywhere. You must mention a serializer inside your view class to help swagger generate params for CBV. Follow the documentation steps carefully, and you ll end up having your issue solved hopefully. Let me know if my input is required at some point.

m-haziq avatar Nov 16 '17 09:11 m-haziq

in settings.py add:

SWAGGER_SETTINGS = { 'JSON_EDITOR': True, }

image

it doesn't work

Jazzy818 avatar Jan 11 '19 03:01 Jazzy818

SWAGGER_SETTINGS = { 'JSON_EDITOR': True, }

Is not working to show the INPUT boxes for each JSON param of request body for POST/PUT. Any more changes to do?

Using: Django==2.1.8 django-rest-swagger==2.2.0 djangorestframework==3.9.4

sam25488 avatar Jun 27 '19 06:06 sam25488

solution :

 SWAGGER_SETTINGS =
         {            
              'JSON_EDITOR': True,       
        }

also added parsers DRF SETTINGS in this order:

  'DEFAULT_PARSER_CLASSES': (
          'rest_framework.parsers.FormParser',
          'rest_framework.parsers.MultiPartParser',
          'rest_framework.parsers.JSONParser',
   )

sam25488 avatar Jun 27 '19 14:06 sam25488

hii guys , to solve this problem 1 use package drf-yasg for swagger generation 2 using this package use auto_schema_generator for generating schema .(given in the docs of drf-yasg) for passing parameter in post and put method in swagger

pratikwinbold avatar Apr 25 '20 06:04 pratikwinbold