1

Part of my Flask code:

@app.route('/api/post', methods=['POST']) 
def post():
    body = request.get_json()
    json_body = json.loads(body)
    new_id = mongo.db.Projects.insert(json_body)
    return str(new_id)

Script to post a new database entry:

payload =  { 'ProjectName' : 'KdB Test Project' }
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
r = requests.post('http://localhost:5000/api/post', headers=headers, data=json.dumps(payload))

I keep getting json decoder TypeError problems, e.g.

TypeError: expected string or buffer
2016-08-16 15:19:31,388 - werkzeug - INFO - 127.0.0.1 - - [16/Aug/2016 15:19:31] "POST /api/post HTTP/1.1" 500 -

I have tried several things, incl. posting strings. Any clue what is wrong with the way I post a dictionary? The problem appears to be at the point of body = request.get_json(). I don't think I am picking up any data...

0

2 Answers 2

5

You don't need to loads request message to get dict format. Information stored in body variable is already in dict form. Simply doing the following should remove the error:

@app.route('/api/post', methods=['POST']) 
def post():
    body = request.get_json()
    # json_body = json.loads(body)
    new_id = mongo.db.Projects.insert( body )
    return str( new_id )
Sign up to request clarification or add additional context in comments.

Comments

0

http://flask.pocoo.org/docs/0.11/api/#flask.Request.get_json

get_json is probably returning a dict already, so you don't need to call json.loads(body) (this is what most likely causes the TypeError).

@app.route('/api/post', methods=['POST']) 
def post():
    json_body = request.get_json()
    new_id = mongo.db.Projects.insert(json_body)
    return str(new_id)

4 Comments

Thanks, friends. Unfortuntately, it does not solve my problem. I am getting the following errors:
Still getting that error:File "c:\Python27\Lib\json_init_.py", line 338, in loads return _default_decoder.decode(s) File "c:\Python27\Lib\json\decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer
Thanks for your help. Problem solved. Rebooting the system and/or changing the @app.route to a different path helped.
@KeesdeBlois: please consider accepting the answer that helped you (the tick under the answer score).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.