1

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.