Home > front end >  BrowsableAPI not working with functional views
BrowsableAPI not working with functional views

Time:01-28

How do I make BrowsableAPI work with functional views? For example, let's say I have

from django.http import HttpResponse, JsonResponse
from rest_framework import generics
from django.views.decorators.csrf import csrf_exempt

from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from .models import Snippet, SnippetSerializer


@api_view(['GET', 'POST'])
@csrf_exempt
def snippet_list(request):
    """
    List all code snippets, or create a new snippet.
    """

    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

When I register in the url and acces it, the browser gives me the raw json, not the browsableapi version of it. How can I make it work? I looked up the documentation and posts but couldnt find anything, everyone is either using classes based or generics. I know this way of making views is not ideal, but I still want to know how to make a functional view "Browsable".

#snippets/urls.py
from django.urls import path
from .views import snippet_list

urlpatterns = [
    path('', snippet_list, name='snippets')
]
#project/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('snippets.urls'))
]

CodePudding user response:

Was going through your code and found

return JsonResponse(serializer.data, safe=False)

in your Get method and I think this is the issue, maybe.

try with -

from rest_framework.response import Response
return Response(serializer.data)
  •  Tags:  
  • Related