1

When trying to get the text of the added comments, I am getting the key error in flask.request.form with the following curl command. I try to print out flask.request.form but it was empty. How to fix it?

curl command to add new comment:

curl -ib cookies.txt   
--header 'Content-Type: application/json'   
--request POST   
--data '{"text":"Comment sent from curl"}'  
http://localhost:8000/api/v1/p/3/comments/

ERROR:

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'text'

My comment obj:

  <form id="comment-form">
  <input type="text" value=""/>
  </form>

My flask.api python file that would return new comment dictionary:

@app.route('/api/v1/p/<int:postid>/comments/', methods=["POST"])
def add_comment(postid):
     db = model.get_db()
    owner = flask.session["username"]
    query = "INSERT INTO comments(commentid, owner, postid, text, created) VALUES(NULL, ?, ?, ?, DATETIME('now'))"
    db.execute(query, (owner, postid, flask.request.form["text"]))
    last_id = db.execute("SELECT last_insert_rowid()").fetchone()["last_insert_rowid()"]
    get_newest_comment_query = "SELECT * FROM comments WHERE commentid = ?"

    comment = db.execute(get_newest_comment_query, (last_id,)).fetchone()
    print('get comment: ', comment)
    return flask.jsonify(comment), 201
Dharman
  • 30,962
  • 25
  • 85
  • 135
Erin
  • 83
  • 1
  • 9

2 Answers2

0

Your HTML form is not correctly configured.

  1. You are sending a GET request and your flask is only accepting POST.
  2. flask.request.form["text"] is asking for an input named text, but your textbox does not have any name.
  3. There is no submit button.

You can fix it in this way:

<form id="comment-form" method="post">
    <input type="text" value="" name="text" />
    <input type="submit" />
</form>

Could have been easier for you to debug if you would have known more about response codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status.

Since your are using request.form, tour curl can be simplified like this:

curl --form "text=some_text_here" http://localhost:8000/api/v1/p/3/comments/

Hope this helps. Good luck.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
0

Adding to @Harshal's answer, While using curl, seems like you're accessing the request data incorrectly. Since the Content-Type for the request is set as application/json, you need to access the request data using flask.request.json - more details

Or you can update the curl command like below,

curl -ib cookies.txt   
  --request POST   
  --data-urlencode "text=Comment sent from curl"  
  http://localhost:8000/api/v1/p/3/comments/

in this case, curl will automatically use Content-Type application/x-www-form-urlencoded and your application will be able to read the request data using flask.request.form

Sujan Adiga
  • 1,331
  • 1
  • 11
  • 20