[Fixed]-Django Rest Framework: Output in JSON to the browser by default

27👍

At the settings.py need to add the following setting..

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
    )
}

For more detail visit : http://www.django-rest-framework.org/api-guide/settings/

4👍

@Devasish gives a default for all views, but you can also set the renderers used for an individual view, or viewset, as in the following example from the DRF doco:

APIView class-based views.

from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView

class UserCountView(APIView):
    """
    A view that returns the count of active users in JSON.
    """
    renderer_classes = [JSONRenderer]

    def get(self, request, format=None):
        user_count = User.objects.filter(active=True).count()
        content = {'user_count': user_count}
        return Response(content)

1👍

The browsable API of rest-framework is a json. Is not necessary write

?format=JSON

in the url, is just UI

if you curl the api root:

curl -I http://drf-demo.herokuapp.com/api/universities/
HTTP/1.1 200 OK
Connection: keep-alive
Server: gunicorn/19.4.5
Date: Fri, 04 Aug 2017 08:12:52 GMT
Transfer-Encoding: chunked
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Via: 1.1 vegur
👤Mattia

Leave a comment