Django Rest Framework: How to enable swagger docs for function based views

前端 未结 3 517
忘了有多久
忘了有多久 2021-01-17 09:10

I went through Django REST Swagger 2.1.2 documentation. When I tried with class based views, it was working fine.

But i did not find any reference on how to enable s

3条回答
  •  终归单人心
    2021-01-17 09:32

    Add the following in your views.py

    Imports

    from rest_framework.schemas import AutoSchema
    from rest_framework.compat import coreapi
    
    #creating custom class 
    class CustomSampleSchema(AutoSchema):
        def __init__(self):
            super(CustomSampleSchema, self).__init__()
    
        def get_manual_fields(self, path, method):
            extra_fields = [
                coreapi.Field('field1', required=True, location='form', description='', type='', example=''),
                coreapi.Field('field2', required=False, location='form', description='', type='', example=''),
                coreapi.Field('field3', required=False, location='form', description='', type='', example='')
    
            ]
            manual_fields = super().get_manual_fields(path, method)
            return manual_fields + extra_fields
    

    This is the function you're writing swagger doc for.

    @api_view(['post'])
    @schema(CustomSampleSchema())
    @csrf_exempt
    def func_name(request, param):
    """
    Your function definition below
    """
    

    Sample json input

    {"name": "['name1', ]",
    "places": "['place1', 'place2']",
    "key":"12345"}
    

提交回复
热议问题