'NoneType' object has no attribute 'get' Python Flask login function

I’m trying to create a login function using Python Flask to authenticate my APIs but when trying to get the email and password to authenticate these I get the following error:

'NoneType' object has no attribute 'get'

Below is the code for the login function

@flask_app.route('/login', methods=['POST'])
def login():

    email = request.json.get('email', None)
    password = request.json.get('password', None).encode('UTF-8')

    #print(email)
    #print(password)

    if not email:
        return('Missing email', 400)
    if not password:
        return('Missing password', 400)
    
    user = db.session.query(User).filter(User.email == email).first() or None
    if user is None:
        return('Wrong email or password!'), 400

    hashed_password = bcrypt.checkpw(base64.b64encode(sha256(password).digest()), user.hashed_password)
    if hashed_password:
        access_token = create_access_token(identity=user.id)
        refresh_token = create_refresh_token(identity=user.id)
        return jsonify(access_token)

I am using Postman to test the function and have email and password values as below (example values):

{
    'email': example@example.com'
    'password': 'example'
}

Why is it unable to retrieve they values using the request.json.get function?

>Solution :

In postman set in the headers section the Content-Type of your request to application/json:
enter image description here
Also pay attention to your json, it is incorrect:

{
    "email": "example@example.com",
    "password": "example"
}

Use this tool to test your json.

Leave a Reply