Reputation: 101
Even following many example here & there, i can't get my API work in POST Method. Here the code about it :
from flask import Flask, jsonify, request
@app.route('/api/v1/lists', methods=['POST'])
def add_entry():
print("p0")
content = request.get_json()
appname = content.get('title')
print(content)
print(appname)
When i query with curl (i'm running it on Windows):
curl.exe -i -H "Content-Type: application/json" -X POST -d '{"title":"titi"}' http://localhost:5000/api/v1/lists
curl.exe -i -H "Content-Type: application/json" -X POST -d "{"""title""":"""Read a book"""}" http://localhost:5000/api/v1/lists
I have always a 400 error in return:
HTTP/1.0 400 BAD REQUEST Content-Type: text/html Content-Length: 192 Server: Werkzeug/0.12.1 Python/3.6.0 Date: Tue, 04 Apr 2017 21:55:29 GMT 400 Bad Request Bad Request The browser (or proxy) sent a request that this server could not understand.
I dont see where the error is.
Thanks for your help.
Upvotes: 6
Views: 43113
Reputation: 91
Even with the "working" code, in case of your if-block failure (when value1
and value2
is None
) will cause the same error, since you are not handling the else
part of the if-block. The corrected should be:
@app.route('/api/v1/list', methods=['POST'])
def add_entry():
print("p0")
request_json = request.get_json()
value1 = request_json.get('First_Name')
value2 = request_json.get('Last_Name')
response_content = None
if value1 is not None and value2 is not None:
print("p3")
cursor.execute("INSERT INTO person (first_name,last_name) VALUES (%s,%s)", (value1, value2))
response_content = conn.commit()
return jsonify(response_content)
Of course you may want something better than None
as the response.
Upvotes: 7
Reputation: 101
Here a code working in my case :
@app.route('/api/v1/list', methods=['POST'])
def add_entry():
print("p0")
request_json = request.get_json()
value1 = request_json.get('First_Name')
value2 = request_json.get('Last_Name')
if value1 is not None and value2 is not None:
print("p3")
cursor.execute("INSERT INTO person (first_name,last_name) VALUES (%s,%s)", (value1, value2))
data = conn.commit()
return jsonify(data)
Upvotes: 1
Reputation: 1807
Your add_entry
function isn't returning a response. You must return something even if it's just return 'OK'
.
EDIT: You're still not returning anything. In Flask
the Python print
statement is not the equivalent of PHP's echo
. All print
does is print to the console. You still have to return a value. If what you need is to return content
and appname
JSON encoded, then add
return json.loads({'contents': contents, 'appname': appname})
to the end of your function.
And to be clear in Flask views must return a value. That Python functions implicitly return None is inconsequential. The error that's occurring is that your function has no return statment.
Upvotes: 1