0

I am using django v2.2.4 and need to access request body data.

Here's my code:

@api_view(['POST'])
@renderer_classes((JSONRenderer,))
def index(request):
    if request.method == 'POST':
        results= []
        data = JSONParser().parse(request)
        serializer = ScrapeSerializer(data=data)

        if serializer.is_valid():           
            url = request.data.url
            #url = request.POST.get('url')

But I get this error:

RawPostDataException at /scrape/
You cannot access body after reading from request's data stream

Here's the request body:

{
    "url": "xyz.com"
}

How can I access the request body?

Azima
  • 3,835
  • 15
  • 49
  • 95

2 Answers2

0

I have found this SO post that related to this issue, Exception: You cannot access body after reading from request's data stream

Anyway use request.data instead of request.body in DRF

@api_view(['POST'])
@renderer_classes((JSONRenderer,))
def index(request):
    if request.method == 'POST':
        results = []
        serializer = ScrapeSerializer(data=request.data)

        if serializer.is_valid():
            url = request.data["url"]

The request.data returns the parsed content of the request body and it will be dict like object, hence the dot operation (request.data.url) won't works here.

JPG
  • 82,442
  • 19
  • 127
  • 206
0

To access the request body of a POST request, you could do this by url = request.POST.get("url")

Shivam Kohli
  • 449
  • 4
  • 6