Object of type bytes is not JSON serializable when trying to return jwt_token

Issue

Really confused because this functionality was working a few days ago and I made no substantial changes to my code.

I am getting this traceback:

Traceback (most recent call last):
  File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
  File "C:\Users\15512\anaconda3\lib\site-packages\django\core\serializers\json.py", line 105, in default
    return super().default(o)
  File "C:\Users\15512\anaconda3\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

To summarize, I am sending a name to the Twilio library with the expectation of receiving a JWT_token. The API endpoint would then return a dict with a key: title and jwt_token

This is what my view for the end point looks like:

class TokenView(View):
    def get(self, request, username, *args, **kwargs):
        voice_grant = grants.VoiceGrant(
            outgoing_application_sid=settings.TWIML_APPLICATION_SID,
            incoming_allow=True,
        )
        access_token = AccessToken(
            settings.TWILIO_ACCOUNT_SID,
            settings.TWILIO_API_KEY,
            settings.TWILIO_API_SECRET,
            identity=username
        )
        access_token.add_grant(voice_grant)
        jwt_token = access_token.to_jwt()
        full_data = {'token': jwt_token}
        # print(type(jwt_token))
        return JsonResponse(json.dumps(full_data), content_type="application/json", safe=False)

I’ve also tried to have this in the return statement:

JsonResponse({"token": jwt_token})

Solution

access_token.to_jwt() returns a byte, simply decode the token: access_token.to_jwt().decode()

Full code:

class TokenView(View):
    def get(self, request, username, *args, **kwargs):
        voice_grant = grants.VoiceGrant(
            outgoing_application_sid=settings.TWIML_APPLICATION_SID,
            incoming_allow=True,
        )
        access_token = AccessToken(
            settings.TWILIO_ACCOUNT_SID,
            settings.TWILIO_API_KEY,
            settings.TWILIO_API_SECRET,
            identity=username
        )
        access_token.add_grant(voice_grant)
        jwt_token = access_token.to_jwt()
        full_data = {'token': jwt_token.decode()}
        # print(type(jwt_token))
        return JsonResponse(json.dumps(full_data), content_type="application/json", safe=False)

That should work.

Answered By – Emmanuel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published