1

Flask code -

 @app.route('/messages', methods = ['POST'])
 def api_message():

    if request.headers['Content-Type'] == 'text/plain':
       return "Text Message: " + request.data

    elif request.headers['Content-Type'] == 'application/json':
        f = open(filename,'r')
        l = f.readlines()
        f.close()
        return len(l)

On running, I get error as -

curl -H  "Content-Type:application/json" -X POST http://127.0.0.1:5000/messages --data filename=@hello.json 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.</p>

Am I accessing the curl param wrong (filename)? Or I am sending the file in wrong way?

Also Upload a file to a python flask server using curl

Tried doing

   f = request.files['filename'] 

Still, same error.

Community
  • 1
  • 1

1 Answers1

2

What your curl command code is doing is reading the file hello.json and putting it in the body of the request. (This feature is actually very useful if you have a large chunk of JSON you need to send to the server).

Normally in application/json requests you send the JSON as the body of the request, so this may be what you want. You can use request.get_json to get this data as a Python dictionary.

If you want to upload an actual file - like uploading a picture - you want multi part form encoding, which you tell curl to send via the -F parameter. (See also: an SO answer about this: https://stackoverflow.com/a/12667839/224334 ).

Community
  • 1
  • 1
RyanWilcox
  • 13,890
  • 1
  • 36
  • 60
  • Problem arose because I had filename=@hello.json in curl. curl -H "Content-Type:application/json" -X POST http://127.0.0.1:5000/messages --data @hello.json and request.get_json seems to solve the issue. Thank you so much! – Kinara Shah Jul 20 '16 at 03:54