Validation is the action of checking or proving the validity or accuracy of something or an object, In this case a user input data. It helps check that the inputs required are standard and meet a specific given requirement


In Python, this can be done in several other ways. Before we get down, this tutorial assumes that you know how to create endpoints and you have enough knowledge to create endpoints to perform CRUD(create, read, update, delete) operations. Incase you need more insites on how to do this, please checkout my tutorial on Building API using python flask framework or Building RESTful APIs using Flask


There are several ways of doing this and We are going to look at this three major one. In this tutorial we are going to consider this simple POST endpoint in flask, see below:

We got this sample code from here

@app.route('/adduser', methods=['POST'])
def add_user():
    data = request.get_json()
    name = data['name']
    email = data['email']
    tell = data['tell']

    new_user = {
        "name": name,
        "email": email,
        "tell" : tell
    }
    user_list.append(new_user)
    return make_response(jsonify({
        "Message": "User added succesfully",
        "user name": new_user['name']
    }), 201)

Option 1 – Using if else statements in python

Decision making is required when we want to execute a code only if a certain condition is satisfied. The if…elif…else statement is used in Python for decision making.

if test expression:     
Body of if
else:
Body of else

Example

@app.route('/adduser', methods=['POST'])
def add_user():
    data = request.get_json()
    name = data['name']
    email = data['email']
    tell = data['tell']
    if not name:
        return "Name is missing"
    elif not email:
        return "Email is missing"
    elif not tell:
        return "Tell is missing"
    elif len(name) < 3:
        return "Name is too short"

    new_user = {
        "name": name,
        "email": email,
        "tell": tell
    }
    user_list.append(new_user)
    return make_response(jsonify({
        "Message": "User added succesfully",
        "user name": new_user['name']
    }), 201)

In the code above, we validated if the user inputs name, email and tell were provided and also validated the length of name to be more than three characters. You can basically add more if elses and see how this is gonna work around for your code

Validating user input
Validating user input

Option 2 – Using methods and functions

Using this method, we are going to create a function validateuser(user_data={}) which we will then call at the top bottom of our new user dictionary just before appending data

Here is the function:

def validateuser(new_user):
    """This function validates the new user input and rejects or accepts it"""
    for key, value in new_user.items():
        # ensure keys have values
        if not value:
            return "{} is lacking. It is a required field".format(key)
        # validate length
        if key == "email" or key == "name":
            if len(value) < 3:
                return "The {} provided is too short".format(key)
            elif len(value) > 15:
                return "The {} provided is too long".format(key)

The function takes in a parameter new_user which is a dictionary. Splits it into two key and value using the item() then loops through the data in correspondence to its data elements.

And is our updated endpoint:

@app.route('/adduser', methods=['POST'])
def add_user():
    data = request.get_json()
    name = data['name']
    email = data['email']
    tell = data['tell']

    new_user = {
        "name": name,
        "email": email,
        "tell": tell
    }
    validateuser(new_user)

    user_list.append(new_user)
    return make_response(jsonify({
        "Message": "User added succesfully",
        "user name": new_user['name']
    }), 201)

We then call the function in the block after our dictionary.

I must add this option works pretty well especially when you can manage and use error handlers (I will rewrite about this).

Option 3 – Using flask mashmellow

Flask mashmellow is one of those extensions that you can use to validate user inputs. It provide you with one of the options of define or telling the endpoints what to expect in the request which if its not provided it throws in an error.

When using them, I would encourage you to use flask restplus since the package comes with defined Namespace and fields.

To get started yo just need to define what you want in the request body.


api = Namespace('adding a user', description='for adding a user')
n_user = api.model('new user request', {
    'name': fields.String(required=True, description="user's name"),
    'email': fields.String(required=True, description="user's email address"),
    'tell': fields.String(required=True, description="user's tell")
})

Then call the decorator ontop of the route function or method

@app.route('/adduser', methods=['POST'])
@app.expect(n_user, validate=True)
def add_user():
    data = request.get_json()
    name = data['name']
    email = data['email']
    tell = data['tell']

    new_user = {
        "name": name,
        "email": email,
        "tell": tell
    }
    _validateuser(new_user)

    user_list.append(new_user)
    return make_response(jsonify({
        "Message": "User added succesfully",
        "user name": new_user['name']
    }), 201)

As you might have notice, Most often than note, this is commonly used with the option 2. Also the sample for the expected namespace is usually put inside the serializers.py as it can contain all expected fields for the app.

So having learnt all the three options, which one do you feel ready and best to use, let me know in the comment section of the tutorial.

Did you like it? let us know about the same as well.

1 COMMENT

  1. Thanks for the tutorial.
    I have a question how would you validate the tell to be strictly integers .I was thinking to change the data type to int when specifying the type of input but it’s bringing an error when I test it on postman

LEAVE A REPLY

Please enter your comment!
Please enter your name here