Home > Mobile >  Flask Rest API View Returning Invalid Response
Flask Rest API View Returning Invalid Response

Time:11-21

I am trying to test an endpoint in postman for a flask API, and I am having this error below

TypeError: The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers).

The function is given below

auth = Blueprint("auth", __name__, url_prefix="/api/v1/auth")

@auth.post('/register')
def register():
    username = request.json['username']
    password = request.json['password']
    email = request.json['email']
    

    if len(password) < 6:

        return jsonify({'error': "Password is too short"}),
        HTTP_400_BAD_REQUEST 

    if len(username) < 3: 
        return jsonify({'error': "User is too short"}),
        HTTP_400_BAD_REQUEST

    if username.isalnum() or " " in username: 
        return jsonify({'error': "User is too short"}),
        HTTP_400_BAD_REQUEST

    if not username.isalnum() or " " in username: 
        return jsonify({'error': "Username should be alphanumeric, also no spaces"}), 
        HTTP_400_BAD_REQUEST 

    if not validators.email(email):
        return jsonify({'error': "Email is not valid"})
        HTTP_400_BAD_REQUEST

    if User.query.filter_by(email=email).first() is not None: 
        return jsonify({'error': "Email is taken"}), HTTP_409_CONFLICT

    if User.query.filter_by(username=username).first() is not None: 
        return jsonify({'error': "username is taken"}), HTTP_409_CONFLICT

        
    pwd_hash=generate_password_hash(password)

    user = User(username=username, password=pwd_hash, email=email)

    db.session.add(user)
    db.session.commit()

    return jsonify({
        'message': "User created", 
        'user': {
            'username': username, 'email': email
        }
    }), HTTP_201_CREATED

The test input on postman to the route http://127.0.0.1:5000/api/v1/auth/test is :

{
    "username": "username",
    "password": "password",
    "email": "[email protected]"
}

CodePudding user response:

well you forgot to add a , in the below code

    if not validators.email(email):
        return jsonify({'error': "Email is not valid"})
        HTTP_400_BAD_REQUEST

this is causing this Typeerror

just change this to

return jsonify({'error': "Email is not valid"}),
        HTTP_400_BAD_REQUEST
  • Related