Get Data JSON in Flask

33,097

Solution 1

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.

Solution 2

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.

Share:
33,097
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    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.