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.
Your
add_entry
function isn't returning a response. You must return something even if it's justreturn 'OK'
.EDIT: You're still not returning anything. In
Flask
the Pythonprint
statement is not the equivalent of PHP'secho
. Allprint
does is print to the console. You still have to return a value. If what you need is to returncontent
andappname
JSON encoded, then addreturn 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.
Here a code working in my case :
Even with the "working" code, in case of your if-block failure (when
value1
andvalue2
isNone
) will cause the same error, since you are not handling theelse
part of the if-block. The corrected should be:Of course you may want something better than
None
as the response.