4

I'm working on creating a RESTAPI using DRF(Django Rest Framework). API just receives the users twitter handle and returns his twitter data.

Here, I'm not using model here because it's not required.

Should I use a serializer here? If so why? Now I'm able to return the data without using a serializer. Moreover, My API is not web-browsable. How should I make it web-browsable: which is one of the best features of DRF.

Edit:1

I'm using Functions in Views.

@api_view(['GET'])
@csrf_exempt
def getdetails(request):

    call the twitter api
    receive the data
    return HttpResponse(JsonResponse( {'data': {'twitter_id':id,'tweets':count,'Followers':followers,'following':count_follow}}))

In the browser I'm just seeing JSON data like this.

{"data": {"twitter_id": 352525, "tweets": 121, "Followers": 1008, "following": 281}}

1 Answer 1

6

You can use Serializer for the result

class SampleSerializer(serializers.Serializer):
    field1 = serializers.CharField()
    field2 = serializers.IntegerField()
    # ... other fields

Usage

my_data = {
    "field1": "my sample",
    "field2": 123456
}

my_serializer = SampleSerializer(data=my_data)
my_serializer.is_valid(True)
data = my_serializer.data

You'll get serialized data in data variable (you can use my_serializer.data directly)

Should I use a serializer here?

It's up to you, because if you wish to show the response JSON without any modification from the Twitter API, you can go without DRF serializer. And If you wish to do some formatting on the JSON, my answer will help you

My API is not web-browsable. How should I make it web-browsable?

Maybe you followed wrong procedure. Anyway we can't say more on this thing without seeing your code snippets

Update-1

from rest_framework.response import Response


@api_view(['GET'])
@csrf_exempt
def getdetails(request):
    call the twitter  api
    twitter_api = get_response_from_twitter()  # Json response
    return Response(data=twitter_api)
Sign up to request clarification or add additional context in comments.

5 Comments

hello Jerin. thanks for your response. Modified the question with sample code. Please suggest a way to make it web-browsable
Thank you jerin. is web-browsable api possible without using Serializer ? If so please let me know how?.
In your case, api_viewdecorator will do it. Unfortunately, you'd used HttpResponse so, it forcefully converted the we-browsable API to an HTML like response
Did you tried Update-1 section of my answer? It should work,
Hello Jerin, I added response Instead of HttpResponse(JsonResponse()). and it worked. Thank you :) it's now web-browsable and yea I haven't used serializer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.