I am working on a rest api using flask. Currently the code for the client is as follows:
new_data = {'msg': message,
'rec':rec_id,
'snd':my_id}
requests.post("http://localhost:33/api/resources/messages/all", json = new_data)
I did print out new_data and it does print fine it does print out fine
{'msg': 'This is a message', 'rec': 1, 'snd': 0}
and the code in the rest api is:
@app.route('/api/resources/messages/all', methods=['GET', 'POST'])
def api_messages():
if request.method == "GET":
return jsonify(messages)
if request.method == "POST":
sentmsg = request.json
print (sentmsg)
changing
sentmsg = request.json
to
sentmsg = request.get_json()
did not change anything as it still results in the same error. Specifying the content type also did not result in any changes to the result.
However this code results in the error when attempting to post it.
TypeError: Object of type type is not JSON serializable
How can I change this code in order to make it so the json is passed to the rest api and can be printed out in json form.
CodePudding user response:
The issue did not originate from the code shown in the initial post. The error originates at the start of the code where I declared two of the variables used here:
my_id = int rec_id = int
since these 2 variables did not have a value it was causing issue when being called. As such it resulted in the error message "TypeError: Object of type type is not JSON serializable" (This error message itself giving a good indicator that one or more of the variables used were likely blank and held no value, Thus making it unable to specify the data type in the message).
As such giving these variables an actual value caused the program to work fine. A second error that only become obvious after was that request.get_json needed to have brackets after get_json, Making it request.get_json()