Edgar Navasardyan
Edgar Navasardyan

Reputation: 4501

How to deserialize base64-encoded data and use it with DRF

My goal is to come up with an endpoint that gets a base64-decoded string. This is based described by an example

My input JSON looks like this:

{
    "encoded_data": "a2F0aWUsIGpvaG5zLCBrYXRpZUBnbWFpbC5jb20KdG9tbXksbGVlLHRvbW15QGdtYWlsLmNvbQ=="
}

I have tried to implement it the following way, but I end up with the following error message:

JSON parse error - Expecting value: line 1 column 1 (char 0) 

Looks like I've messed up the concepts. Really need help on this:

class UsersFileUpload(APIView):
    #parser_classes = (MultiPartParser,)

    def post(self, request):
        stream = base64.b64decode(request.data['encoded_data'])

        stream = io.BytesIO(stream)
        data = JSONParser().parse(stream) 
        serializer = UsersSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Upvotes: 0

Views: 1188

Answers (1)

A. J. Parr
A. J. Parr

Reputation: 8026

I don't think you're decoding your text correctly, you shouldn't need to use BytesIO.

You should decode the byte string returned from b64decode and then pass it to the JSONParser.

b64decoded_data = base64.b64decode(request.data['encoded_data']).decode('UTF-8')
data = JSONParser().parse(b64decoded_data)

Upvotes: 1

Related Questions