0

How can I extract JSON data returned by Flask ?

back-end:

response_obj = {
        'status': 'fail',
        'message': 'Invalid Payload'
    }
return jsonify(response_obj), 500

front-end:

import requests

data = # some json data here
response = requests.post('http://18.133.238.8/auth/login', json=data)

I've tried:

print(dir(response))

which gave me:

...
...
__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', '_next', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'is_permanent_redirect', 'is_redirect', 'iter_content', 'iter_lines', 'json', 'links', 'next', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']

that tipped me off to use:

print(response.json)

or:

print(response.json())

I'm just getting errors. How do I get the JSON data from response ?

Mark
  • 1,385
  • 3
  • 16
  • 29
  • response.json() should be correct. We can't help you unless you give us specifics about what errors you are getting. – fooiey Oct 08 '20 at 14:34
  • 1
    I guess this is because `500` error that you are returning `return jsonify(response_obj), 500`. if it's ok, then you can skip custom status code, because `jsonify` returns 200 by default. Also try `print(response.content)` this might give some clues or `print(response.status_code)` – simkusr Oct 08 '20 at 14:34
  • No, I'm returning 500 deliberately. It's within block of code that handles various errors. – Mark Oct 08 '20 at 15:03
  • @simkus `response.content` worked beautifully ! So I was just using wrong attribute. Thank you @simkus ! Feel free to post it as solution. – Mark Oct 08 '20 at 15:08

1 Answers1

1

Try this way:

from requests import request

response = request('POST', "<URL here>")
print(response.json())
Narendra
  • 21
  • 4
  • I'm passing json data to the post request. How do I pass it using your way ? Your way doesn't seem to take in the `json` parameter. – Mark Oct 08 '20 at 15:09