Alok Singh
Alok Singh

Reputation: 116

Python 3 Flask Rest Api: "request.get_json()" gives TypeError: 'NoneType' object is not subscriptable

I am creating a route in python flask which will server as rest api to register a user. when I try to get json data passed through postman in POST method, I get error TypeError: 'NoneType' object is not subscriptable

my request from postman: http://127.0.0.1:5000/register

raw input: {"username":"alok","password":"1234"}

my route and function:

@app.route('/register', methods=['GET', 'POST'])
def signup_user():
    data = request.get_json()
    return data['username']

As per my knowledge above function should return : "alok"

but i get error: TypeError: 'NoneType' object is not subscriptable

Any help will be appreciated

Upvotes: 1

Views: 3741

Answers (2)

mohamed moalla
mohamed moalla

Reputation: 1

Add Content-Type : application/json to the header of your Post API request .

Upvotes: 0

Alok Singh
Alok Singh

Reputation: 116

I spending few hours over internet I got answer from flask official website

I had not set mimetype while making request.
If the mimetype does not indicate JSON (application/json, see is_json()), this returns None.
request.get_json() is used to Parse data as JSON. actual syntax is get_json(force=False, silent=False, cache=True)

Parameters
force – Ignore the mimetype and always try to parse JSON.
silent – Silence parsing errors and return None instead.
cache – Store the parsed JSON to return for subsequent calls.

So finally I have changed my code to

@app.route('/register', methods=['GET', 'POST'])
def signup_user():
    data = request.get_json(force=True)
    return data['username']

It is resolved.

Upvotes: 7

Related Questions