Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework: Output in JSON to the browser by default

I do not want to write ?format=JSON in the URL. It should return JSON by default with djangorestframework

like image 248
Devasish Avatar asked Aug 04 '17 05:08

Devasish


3 Answers

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/

like image 129
Devasish Avatar answered Nov 16 '22 02:11

Devasish


@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)
like image 37
MagicLAMP Avatar answered Nov 16 '22 03:11

MagicLAMP


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
like image 23
Mattia Avatar answered Nov 16 '22 01:11

Mattia