Data Validation

Data validation exemplified through a POST request

ยท

1 min read

Often, if not always, you want to validate an incoming payload to ensure it is passing the necessary parameters. If parameters are missing, you can fast-fail with an InvalidInput-like exception to quickly let the requester know the payload is malformed. Documented below is a simple way to do such validation.

from flask import Flask 
from flask import request
from flask import jsonify

app = Flask(__name__)

@app.route("/create", methods=["POST"])
def create(): 
    payload = request.get_json()
    person: Person = Person(payload)
    return jsonify({"status": "ok"})


class Person: 
    def __init__(self, args): 
        try: 
            self.name = args["name"]
            self.age = args["age"]
            self.address = args.get("address") 

        except Exception as ex:
            raise InvalidInput()


if __name__ == "__main__": 
    app.run(host="0.0.0.0", debug=True, port=8888)

All it consists of is a class whose __init__ sets the parameters according to what is in the payload. If such a value does not exist, an error is thrown. Also notice that in this model parameters can be required or optional.

Unfortunately, this does not validate against extraneous data - it only checks that the required parameters were provided.

This is a rather rudimentary method of data validation and for more complicated validations (including extraneous data validations) using pydantic is preferred.

Maybe the next blog will cover pydantic.

Until then,

Happy coding! ๐Ÿ›‚

P.S. Pydantic extraneous data validation check is here

ย