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.
There are two methods you can use to return JSON data in your Flask application's view: by returning a Python dictionary, or by using Flask's jsonify() method.
It's pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With