drf_openapi icon indicating copy to clipboard operation
drf_openapi copied to clipboard

Feature implementation: Deep request serializer & different serializers for specific response codes

Open dnsdev opened this issue 8 years ago • 3 comments

  • DRF OpenAPI version: based on 1.0.0
  • Python version: *
  • Operating System: *

Description

I extended the drf_openapi Django app to support detailed request serializers for requests. Then I also needed different serializers for different status codes (e.g. 200 has a specific response and some error, maybe 503 has a completely different one). This is already done, but I am not sure if this is compatible to the OpenAPI spec. If you are interested in this feature, then I would fork this and create a pull request.

What I Did

Implemented the above functionality. The drf_openapi module searches automatically for the correct serializer depending on the response code of the views' method. Here are some screenshots of the extended usage: image image

Here is the django code for defining the views' serializers:

@view_config(request_serializer=UserLoginSerializer,
                 response_serializer={
                     200: (UserLoginResponseSerializer, 'Success'),
                     423: (UserLoginFailedResponseSerializer, 'Device not yet verified'),
                     400: (NoValidation, 'Bad Request - Invalid data given')
                 },
                 validate_response=True)
    def create(self, request, *args, **kwargs):
        """
        The user wants to authenticate against the backend and receives a token and his/her user ID on success.
        """
        ..... the views' code .....
        .....
        if something_went_wrong:
            return Response({'message': _('Verify device - email sent'), 'activation_id': device_activation_pin.pk},
                            status=status.HTTP_423_LOCKED)
        .....
        return Response({'message': _('logged in'), 'token': token.key, 'user_id': user.pk,
                         'created': token.created, 'device_id': device.pk},
                        status=status.HTTP_200_OK)

The "NoValidation" class passed as a serializer deactivates response validation for the specific response code.

dnsdev avatar Oct 17 '17 18:10 dnsdev

Ah, I forgot something: I also moved the error_codes from the serializers' Meta class to the view_config decorator.

dnsdev avatar Oct 17 '17 18:10 dnsdev

Have you published the code for this anywhere? This looks like something I would have wanted to do for my project too.

axnsan12 avatar Nov 27 '17 13:11 axnsan12

This is a really good suggestion. I will make sure it land on 2.0

limdauto avatar Dec 17 '17 18:12 limdauto