-1

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.

  • Does this answer your question? [How to get POSTed JSON in Flask?](https://stackoverflow.com/questions/20001229/how-to-get-posted-json-in-flask) – shoaib30 Sep 20 '21 at 10:20
  • You need to set `Content-type` as `application/json` when using `request.get_json()` – shoaib30 Sep 20 '21 at 10:22
  • Content-type should be set automatically if you use json= in the requests.post function – c8999c 3f964f64 Sep 20 '21 at 11:26
  • does this error happen when you try to post the json, or in the api receiving the request? – c8999c 3f964f64 Sep 22 '21 at 12:51
  • @c8999c3f964f64 The error occurs on the client side code when trying to post the json. Switching from request.get_json to request.get_json() results in no real difference and specifying the content-type has not worked either. – Luke Phillips Sep 23 '21 at 07:48

1 Answers1

0

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 issues when it was called. As such it resulted in the error message "TypeError: Object of type type is not JSON serializable" (This error message itself gives 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().

Laurel
  • 5,965
  • 14
  • 31
  • 57