django rest serialize a string when model object is not defined

Question:

having trouble serializer a string during a try/except statement.

here i have a endpoint that calls another function refund the response i get back from that function i’m trying to serialize.

class RefundOrder(APIView):
    def post(self, request, **kwargs):
        print('test')
        body_unicode = request.body.decode('utf-8')
        body_data = json.loads(body_unicode)
        amount = body_data['amount']
        tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id'])

        refund = SquareGateway(tenant).refund(amount)
        serializer = RefundSerializer(refund)
        return  Response(serializer.data)

this is the function that gets called in the post endpoint. i added it in a try statement to handle the errors from square api. if the api call fails, i want to return an error if their is one, else serialize that data.

    def refund(self, order, amount, reason):

        try:
            response = self.client.transaction().create_refund(stuff)
                
            refund = Refund(
                order=order,
                amount=response.refund.amount_money.amount,
            )
            refund.save()
            return refund
        except ApiException as e:
            return json.loads(e.body)['errors'][0]['detail']

this is the the Refundserialize

class RefundSerializer(serializers.ModelSerializer):
    class Meta:
        model = Refund
        fields = ('id', 'amount')

serializing the string doesn’t throw an error it just doesn’t return the error message that im returning.Currently it returns a empty serialized object.

Asked By: David Ramirez

||

Answers:

As far as I understood, You need a custom API exception which returns a custom message.
So, Initially create a custom exception class as below,

from rest_framework.exceptions import APIException
from rest_framework import status


class GenericAPIException(APIException):
    """
    raises API exceptions with custom messages and custom status codes
    """
    status_code = status.HTTP_400_BAD_REQUEST
    default_code = 'error'

    def __init__(self, detail, status_code=None):
        self.detail = detail
        if status_code is not None:
            self.status_code = status_code

Then raise the exception in refund() function.

def refund(self, order, amount, reason):

    try:
        # your code
    except ApiException as e:
        raise GenericAPIException({"message":"my custom msg"})
Answered By: JPG