How to create a custom Swagger schema in Django Rest Framework?

I am having trouble creating a custom smagger scheme in the Django Rest Framework. I read the documentation pages but did not find a clear example on how to create swagger annotations in python.

I know that the swagger / schema documentation is easily generated when using ViewSets in Django. However, I use only APIViews and want to write a custom schema. I tried to create a CoreAPI scheme, but I don’t know how to implement it. I am attaching some of my sample code and some screenshots. Screenshots go from what I have to what I want.

Code example:

urls.py

from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from Views import SampleView as sv
from rest_framework_swagger.views import get_swagger_view
from rest_framework.documentation import include_docs_urls
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.schemas import get_schema_view

schema_view enter code here= get_swagger_view(
    title='Sample API')

urlpatterns = [
    url(r'^sample/$', pv.SampleList.as_view()),
    url(r'^sample/(?P<id>[a-f\d]{24})/$', sv.SampleDetail.as_view()),
    url('^schema/$', schema_view),
]

urlpatterns = format_suffix_patterns(urlpatterns)

views.py

from rest_framework.views import APIView
from Manager.SampleManager import SampleManager as sm

_sampleManager = sm()

class SampleList(APIView):
"""
get:
Return a list of all the existing samples.

post:
Create a new sample.
"""
def get(self, request, format=None):

    return _sampleManager.getAll()


def post(self, request,  format=None):

    return _sampleManager.create( request)


 class SampleDetail(APIView):
   """
   get:
   Get a sample.

   put:
   Update a sample.

   delete:
   Delete a sample.
   """
def get(self, request, id, format =None):
    return _sampleManager.getById( id)

def put(self, request, id, format =None):

    return _sampleManager.update( request, id)

def delete(self, request, id, format =None):

    return _sampleManager.deleteById( id)

Searlizers.py

from rest_framework_mongoengine.serializers import DocumentSerializer
from .modles import Sample, SampleInner
from Serializers.SampleInnerSerializer import SampleInnerSerializer

class SampleSerializer(DocumentSerializer):
    other = SampleInnerSerializer(many=True)
    class Meta:
        model = Sample
        fields = '__all__'

    def create(self, validated_data):
        samples = validated_data.pop('other')
        created_instance = super(SampleSerializer,     self).create(validated_data)

        for sample_data in samples:
            created_instance.other.append(SampleInner(**sample_data))

        created_instance.save()
        return created_instance

    def update(self, instance, validated_data):
        samples = validated_data.pop('other')
        updated_instance = super(SampleSerializer, self).update(instance, validated_data)

        for sample_data in samples:
            updated_instance.other.append(SampleInner(**sample_data))

        updated_instance.save()
    return updated_instance

Schema.py

import coreapi
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import renderers, response

schema = coreapi.Document(
 title='Sample API',
 content={
     'sample': coreapi.Link(
         url='/sample/',
         action='post',
         fields=[
             coreapi.Field(
                name='from',
                required=True,
                location='query',
                description='City name or airport code.'
            ),
            coreapi.Field(
                name='to',
                required=True,
                location='query',
                description='City name or airport code.'
            ),
            coreapi.Field(
                name='date',
                required=True,
                location='query',
                description='Flight date in "YYYY-MM-DD" format.'
            )
        ],
        description='Create partner'
    )
   }
 )

@api_view()
@renderer_classes([renderers.CoreJSONRenderer])
def schema_view(request):
    return response.Response(schema)

enter image description here

enter image description here

enter image description here

enter image description here

+4

Source: https://habr.com/ru/post/1672196/


All Articles