Afolabi Olaoluwa
Afolabi Olaoluwa

Reputation: 1948

How to add a key to my DRF API response value

My API returns just the value. I believe it's my fault but am not very versatile with Python/Django. Any help is appreciated.

What is returned

"This is the message"

What I want:

{
    "message": "This is a message"
}

All I want to do is to add a word as a key

views.py

from rest_framework.response import Response

from id.models import Id
from rest_framework import generics
from id.serializers import IdSerializer
from django.http import Http404
from IPython import embed


class OfferView(generics.RetrieveAPIView):
    serializer_class = IdSerializer
    lookup_field = 'id'

    def get_queryset(self):
        id = self.kwargs['id']
        try:
            return Id.objects.filter(id=id)
        except Mamo.DoesNotExist:
            raise Http404

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()

        serializer = self.serializer_class(queryset, many=True)
        try:
            if serializer.data[0]['offer_id'] is not None:
                result = serializer.data[0]['main_offer']
            elif serializer.data[0]['offer_id'] is None:
                result = serializer.data[0]['extra_offer']
            else:
                result = serializer.data[0]['exceptional_offer']
            return Response(result)
        except IndexError:
            raise Http404

Upvotes: 1

Views: 1046

Answers (2)

hygull
hygull

Reputation: 8740

Just change

Note: The thing is what you will form that you will get, you were just returning string and that was the problem. Now let's convert that to a dictionary (more specifically the JSON here in REST).

serializer.data is a dictionary. You can form a single dictionary containing the keys & values (JSON serializable) you want. Here I just tried to fulfill the need.

result = serializer.data[0]['exceptional_offer']

to

result = {"message": serializer.data[0]['exceptional_offer']}

and the similar for others as well.

Better way:

Just change the following (last lines, I mean try...except)

try:
    if serializer.data[0]['offer_id'] is not None:
        result = serializer.data[0]['main_offer']
    elif serializer.data[0]['offer_id'] is None:
        result = serializer.data[0]['extra_offer']
    else:
        result = serializer.data[0]['exceptional_offer']
    return Response(result)
except IndexError:
    raise Http404

to the below one (writing the same piece of code is like code duplication).

try:
    if serializer.data[0]['offer_id'] is not None:
        # result = serializer.data[0]['main_offer']
        key = 'main_offer'
    elif serializer.data[0]['offer_id'] is None:
        # result = serializer.data[0]['extra_offer']  
        key = 'extra_offer'
    else:
        # result = serializer.data[0]['exceptional_offer']
        key = 'exceptional_offer'

    result = {'message': serializer.data[0][key]}
    return Response(result)
except IndexError:
    raise Http404

Upvotes: 1

Afolabi Olaoluwa
Afolabi Olaoluwa

Reputation: 1948

So, I figured out am just returning the result and not creating a JSON Object.

Adding result = {'message': serializer.data[0]…} to all the variable result in the if..else conditions solves it for me.

Upvotes: 0

Related Questions