Xiaokun
Xiaokun

Reputation: 874

'400 Bad Request' when post json in Flask

My application is very simple,

#@csrt.exempt
@app.route('/preorders/json', methods=['POST'])
def json_create_preorders():
    #print request
    print 'test'
    #print request.json
    print request.mimetype
    print request.json
    print 'aaa',request.get_json(force=True)
    print request.json['product_id']
    if not request.json or not 'product_id' in request.json or not 'customer_name' in request.json or not 'customer_phone' in request.json:
        abort(400)
    preorder=Preorder(request.json['customer_name'],request.json['customer_phone'],request.json['product_id'])
    db.session.add(preorder)
    db.session.commit()
    return jsonify({'status':'success'}), 201

POST json with curl,

curl -i -H "Content-Type: application/json" -X POST -d '{"product_id":"111", "customer_name"="xiaokun", "customer_phone"="1231"}' http://xxxx/preorders/json

Check from server, 'test' and 'request.mimetype' are printed. Then is a 400 response. Anyone can help to have a look?

Upvotes: 9

Views: 22414

Answers (3)

songofhawk
songofhawk

Reputation: 153

It's probably too late to answer, but I have to say that Flask's json checking is sickly strict!

Here's my data:

{
  "id":1,
  "name":"test1",
  "attr2":"data2",
}

It can be passed in all json validator, but Flask think it's invalid, and give a puzzling BAD REQUEST 400 response.

The "Error" is the last comma! Everything is ok, when i changed it to:

{
  "id":1,
  "name":"test1",
  "attr2":"data2"
}

Upvotes: 1

holdlg
holdlg

Reputation: 186

If you are a windows system, you need to modify the json format.

Examples: '{"token":"asdfas"}' replaced by "{\"Hello\":\"Karl\"}"

Upvotes: 10

itzMEonTV
itzMEonTV

Reputation: 20359

Try this

-d '{"product_id":"111", "customer_name":"xiaokun", "customer_phone":"1231"}'

Full syntax

curl -X POST -H "application/json" -d '{"key":"val"}' URL

Upvotes: 10

Related Questions