简体   繁体   中英

Can't send POST request to my basic FLASK Python application

I am trying to test the basic HTTP requests in my simple rest api using Flask framework in Python. The GET method worked just fine not the POST method yet. here is the route:

@app.route('/lang', methods=['POST'])
def addOne():
    language = {'name' : request.json['name']}
    languages.append(language)
    return jsonify({'languages' : languages}) 

My languages dictionary:

languages = [{'name' : 'JavaScript'},{'name' : 'Java'}, {'name' : 'Python'}]

I am trying to use Postman application to post a new language to the dictionary, here is the request:

http://127.0.0.1:8080/lang

And in the body, row I placed this:

{"name" : "C++"}

It gives me this error:

  File "/home/pi/IoT_api/restful.py", line 22, in addOne
    language = {'name' : request.json['name']}
TypeError: 'NoneType' object has no attribute '__getitem__'

The documentation clearly says:

If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.

So make sure to correctly define the 'Content-Type' header with Postman

with the new flask version, change how you get post data from

 language = {'name' : request.json['name']} 

to

language = request.get_json('name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM