So I am having an issue where my Flask server is, to my knowledge, correctly:
- Receiving a JSON object (dict of parameters) from my React web page
- Creating a response prompt using those parameters.
- Calling jsonify on that response prompt.
But it is not updating the Flask server correctly. The server starts with just displaying:
{
"error": "415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not ‘application/json’.",
"success": false
}
and continues to display that even when the @app.route unction is called.
Anyone know what could be the issue here? The plan is to get this response prompt back to another React page that was created when the initial JSON object was created and sent to the Flask server.
`@app.route('/generate-location', methods=['GET', 'POST'])
def process_config():
try:
print("_____Data Here_______")
data = request.get_json()
print(data)
# Extract data from the JSON request
parameters = {
'foo': data.get('foo'),
'bar' :data.get('bar'),
'baz' :data.get('baz')
}
# Call genResponse to create dict containing response prompt
response_dict = gen_response(parameters)
unique = gen_id()
print("______ID Created_______:")
print(unique)
configs[unique] = response_dict
response_dict['unique_id'] = unique
print("______response_______:")
print(response_dict)
return jsonify({'success': True, 'message': response_dict})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
`
I am printing data and response_dict (type is dict) and so far I can see the terminal output for what I want to display and so I think it lies with my requests to and from the server. Does jsonify not automatically correct the content type?
2
Answers
The problem probably comes this line
data = request.get_json()
. Check the Flask documentation what it says about.get_json()
When making a GET or POST request to your Flask server you should add the header
Content-Type: application/json
so it can parse it as json. With curl it can be something like this:curl -X POST -H "Content-Type: application/json" --data "{"foo": "123", "bar": "abc", "baz": "xyz"}" http://localhost:5000/generate-location
with Requests (Python):
requests.post("http://localhost:5000/generate-location", json={"foo": "123", "bar": "abc", "baz": "xyz"})
As said in the other response, you seem to be missing the header
Content-Type: application/json
when you do the request, however, I am intrigued you are able to see the print ofresponse_dict
, (because if it was the header, it would fail in the first line, it won’t continue executing to the print), that makes me think it can be something to do with theresponse_dict
dict. So if adding the header doesn’t work, could you maybe show how theresponse_dict
looks like? There are some dicts that have data types that are not JSON-valid (like NaNs for example)