Last active
June 25, 2019 10:01
-
-
Save vwrs/f32931ee96616165012528bdb7c7b022 to your computer and use it in GitHub Desktop.
Simple Django's class-based View implementation with Swagger support using rest_framework and drf_yasg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework.views import APIView | |
from rest_framework.decorators import parser_classes | |
from rest_framework.parsers import FormParser | |
from django.http import JsonResponse | |
from drf_yasg import openapi | |
from drf_yasg.utils import swagger_auto_schema | |
class TestView(APIView): | |
'''Test API | |
## Test API | |
- The description of Test API | |
- This text is automatically displayed on Swagger. | |
''' | |
# for POST request | |
parser_classes = (FormParser,) | |
text_desc = 'The description of the parameter `test`' | |
err_str = 'param `test` is required but not specified' | |
param_GET = openapi.Parameter('test', openapi.IN_QUERY, | |
description=text_desc, | |
type=openapi.TYPE_STRING, | |
required=True) | |
param_POST = openapi.Parameter('test', openapi.IN_FORM, | |
description=text_desc, | |
type=openapi.TYPE_STRING, | |
required=True) | |
@swagger_auto_schema(manual_parameters=[param_GET], | |
responses={200: 'OK', | |
400: 'Bad Request'}) | |
def get(self, request, **kwargs): | |
if 'test' not in request.query_params.keys(): | |
return JsonResponse(data={'error': self.err_str}, status=400) | |
return JsonResponse(data={'test': request.query_params['test']}, | |
status=200) | |
@swagger_auto_schema(manual_parameters=[ | |
openapi.Parameter('test', openapi.IN_FORM, | |
description=text_desc, | |
type=openapi.TYPE_STRING, required=True)], | |
responses={200: 'OK', | |
400: 'Bad Request'}) | |
def post(self, request, **kwargs): | |
if 'test' not in request.POST.keys(): | |
return JsonResponse(data={'error': self.err_str}, status=400) | |
return JsonResponse(data={'test': request.POST['test']}, status=200) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment