LXG
LXG

Reputation: 1987

How to retrieve Json meta-data from endpoint using django-rest-framework

I'm using Django rest framework to retrieve data from server. Now I create a view:

class Snipped(APIView):

    authentication_classes = (authentication.SessionAuthentication,)
    permission_classes = (permissions.AllowAny,)

    #@ensure_csrf_cookie
    def get(self, request, format=None):
        request.session["active"] = True
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return JsonResponse(serializer.data, safe=False)


    def post(self, request, format=None):

        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

the model is this:

# Create your models here.
class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()

    def __str__(self):
        return self.title

so at this point I'd like to know metadata of data passed to this endpoint, I 've found http://www.django-rest-framework.org/api-guide/metadata/

but if a send OPTION I don't obtain informations about data but only this json answer

{
"name": "Snipped",
"description": "",
"renders": [
  "application/json",
  "text/html"
],
"parses": [
  "application/json",
  "application/x-www-form-urlencoded",
  "multipart/form-data"
],
}

without (see list at http://www.django-rest-framework.org/api-guide/metadata/)

"parses": [
        "application/json",
        "application/x-www-form-urlencoded",
        "multipart/form-data"
    ],
    "actions": {
        "POST": {
            "note": {
                "type": "string",
                "required": false,
                "read_only": false,
                "label": "title",
                "max_length": 100
            }
        }
    }

any idea how can achieve above results with an APIView ?

Upvotes: 1

Views: 1685

Answers (1)

Linovia
Linovia

Reputation: 20996

Actions will only work if the view defines a get_serializer.

You need to define it so you can benefit from the automatic schema generation and return a SnippetSerializer instance.

Refer to generic views to see an implementation example.

Upvotes: 2

Related Questions