Hussein
Hussein

Reputation: 681

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__'

Upvotes: 0

Views: 2957

Answers (2)

felix rono
felix rono

Reputation: 1

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

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

to

language = request.get_json('name')

Upvotes: 0

lee-pai-long
lee-pai-long

Reputation: 2282

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

Upvotes: 1

Related Questions