Get json from request flask

54,068

Solution 1

You are sending form encoded data, not JSON. Just setting the content-type doesn't turn your request into JSON. Use json= to send JSON data.

response = requests.post(url, json={"user": user,"pass": password})

Retrieve the data in Flask with:

data = request.get_json()

Solution 2

I tried executing the same code that you have posted and I was able to fetch values for username and password instead of None.

enter image description here

Solution 3

My initial guess is that since you aren't setting the Content-Type header in your request Flask doesn't understand that it should be able to parse the data. Try adding Content-Type header with the value application/json and see if that gets you where you want.

Another thing to note is when I hit my login page the browser sets the Content-Type header to application/x-www-form-urlencoded and encodes the data as user=asdf&passwd=asdf

Share:
54,068
lads
Author by

lads

Updated on July 12, 2022

Comments

  • lads
    lads almost 2 years

    Client code:

    import requests
    import json
    
    url = 'http://127.0.0.1:5050/login'
    user = "newUser"
    password = "password"
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data={"user": user,"pass": password}, headers = headers)
    

    Server code:

    from flask import Flask, request, make_response
    
    app = Flask(__name__)
    
    
    @app.route('/login', methods=['GET','POST'])
    def login():    
     if request.method == 'POST':
    
        username = request.form.get("user")
        password = request.form.get("pass")
        //more code
        return make_response("",200)
    
    if __name__ == "__main__":
         app.run(host = "127.0.0.1", port = 5050)
    

    The problem is that my username and password are always None.

    I also tried using:

    content = request.get_json(force = True) 
    password = content['pass']
    

    and

    request.form['user']
    

    When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client.

    EDIT:

    I did add json.dumps and used request.get_json() and it worked

  • lads
    lads about 7 years
    Did you use Python3?
  • Afaq
    Afaq about 7 years
    Yes, Python 3.4.4
  • lads
    lads about 7 years
    I added headers = {'content-type': 'application/json'} but it is still not working
  • Afaq
    Afaq about 7 years
    What version of python are you using ?
  • lads
    lads about 7 years
    I was using Python 2.7.10. Now I tried with Python 3.5.1 but I still get None for username
  • Gerad Bottorff
    Gerad Bottorff about 7 years
    Are you still dumping the dict to a string with json.dumps()?
  • user5305519
    user5305519 almost 4 years
    Please share your code instead of an image of it the next time!