marcgibbons / django-rest-swagger

Swagger Documentation Generator for Django REST Framework: deprecated
https://marcgibbons.com/django-rest-swagger/
BSD 2-Clause "Simplified" License
2.59k stars 604 forks source link

Django rest swagger post parameter #629

Open JenishGnanasicamani opened 7 years ago

JenishGnanasicamani commented 7 years ago

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 commented 7 years ago

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

skkap commented 7 years ago

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

marsam commented 7 years ago

@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.

francbartoli commented 7 years ago

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

JenishGnanasicamani commented 7 years ago

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

v-avdeev commented 7 years ago

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 commented 7 years ago

@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 commented 7 years ago

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

JenishGnanasicamani commented 7 years ago

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

likaiguo commented 7 years ago

in settings.py add:

SWAGGER_SETTINGS = { 'JSON_EDITOR': True, }

image

sudaraka94 commented 7 years ago

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

KumarGeoSpark commented 7 years ago

@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

m-haziq commented 6 years ago

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.

GyanP commented 6 years ago

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." 
        })
m-haziq commented 6 years ago

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.

Jazzy818 commented 5 years ago

in settings.py add:

SWAGGER_SETTINGS = { 'JSON_EDITOR': True, }

image

it doesn't work

sam25488 commented 5 years ago

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 commented 5 years ago

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',
   )
pratikwinbold commented 4 years ago

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