Get json from request flask [duplicate]

Client code:

import requests import json url = ' 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 '' [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

0

3 Answers

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() 
0

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

5

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

2

You Might Also Like