drf-yasg custom json body
Asked Answered
S

1

4

How to customize drf-yasg schema in ClassBased django views?

I tried this part of code, but the generated swagger doesn't respect the change.

class CustomView(CreateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = CustomSerializer

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'phone': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'body': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
        }))
    def create(self, request: Request, *args, **kwargs):
        phone = request.data.get('phone')
        body = request.data.get('body')
        ...
Slime answered 24/7, 2020 at 7:9 Comment(0)
S
15

I found it, here is the right code:

class CustomView(CreateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = CustomSerializer
    http_method_names = ['post']

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'phone': openapi.Schema(type=openapi.TYPE_STRING, description='The desc'),
            'body': openapi.Schema(type=openapi.TYPE_STRING, description='The desc'),
        }))
    def post(self, request: Request, *args, **kwargs):
        phone = request.data.get('phone')
        body = request.data.get('body')
        ...

And for IN_QUERY type, like this:

class CustomListView(ListAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = CustomSerializer
    http_method_names = ['get']

    @swagger_auto_schema(manual_parameters=[
        openapi.Parameter('obj_id', openapi.IN_QUERY,
                          type=openapi.TYPE_STRING),
    ])
    def get(self, request, *args, **kwargs):
        obj_id = self.request.DATA.get('obj_id')
Slime answered 24/7, 2020 at 8:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.