Home > front end >  Can I return a single item from a JSON array in POST method API?
Can I return a single item from a JSON array in POST method API?

Time:09-29

As I do POST method, it returns the whole array as a response. Is it possible to return for example only the ID after successful request?

I have

{   "requestid": 1
    "requestname": "Sample request",
    "projectmanager": "Josh",
    "creationdate": "2022-09-26T23:48:00Z"  }

What if I only want to return the result as

{ "requestid": 1 }

Here's my view for reference:

class CreateRequestView(generics.CreateAPIView):
queryset = requestTable.objects.all()
serializer_class = RequestSerializer

Thanks!

CodePudding user response:

Method create is perfect for the job. Firstfully get what a generic response returns, then modify the view's response as you please.

class CreateRequestView(generics.CreateAPIView):
    queryset = requestTable.objects.all()
    serializer_class = RequestSerializer

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        return Response({"requestid": response.get("requestid")})

CodePudding user response:

You can do this with JsonResponse

from django.http import JsonResponse

def your_view():
    ...
    your_id = 1
    return JsonResponse({'requestid':your_id})
  • Related