0

I just starting working with Python and Flask. I created a basic rest and I won't to get data that I send using Postman. Data:

{
    "username": "test",
    "password": "12345"
}

My python code

from flask import Flask, request
...

@app.route("/Test", methods=['POST'])
   def Test():
      print(request.data)
...

I can see in the terminal that it prints b'{\n\t"username": "test",\n\t"password": "12345"\n}' How can I get the values? I'm looking for something like:

request.data.username
request.data.password

How can I do it using python?

BTW, I tried to to request.json and it returned 'none'. Also, request.form returned 'ImmutableMultiDict([])'.

Thanks

realr
  • 3,652
  • 6
  • 23
  • 34
myTest532 myTest532
  • 2,091
  • 3
  • 35
  • 78
  • `json.loads(request.data)` ? – furas Jul 30 '19 at 22:15
  • it seems you would have to use `application/json` in Postman and then you get it in `request.json` (instead of `None`). https://stackoverflow.com/a/20001283/1832058 – furas Jul 30 '19 at 22:19

1 Answers1

1

According to the flask docs, one alternative for you is to use get_json

get_json(force=False, silent=False, cache=True)

So you can try:

print(request.get_json()) # you can use force=True to force a parsing as json.

## access values:

rjson = request.get_json()

username = rjson['username']
psswd = rjson['password']

To really make sure the json is send and read correctly, use the MIME: application/json.

enter image description here

realr
  • 3,652
  • 6
  • 23
  • 34