jeudi 21 octobre 2021

Where to validate parameters sent to an API?

In which place is best practice to validate parameters sent by the user in an API design? By parameter validation I refer to: checking required params are sent, ensure they have correct format and so... Here are a couple of simple examples that validate an id has been sent. It is Python using Flask to illustrate:

A) Add validation logic in the route definition, within the controller.

@api.route('/job', methods=['GET'])
def get_jobs():
    try:
        if params["id"] is None:
            raise Exception("Invalid param ID parameters.")

        job = job_manager.get_job(params["id"])
        return jsonify(job)

B) In the core of the app. This is the business layer, where logic is applied to transform data.

class JobManager:
   def get_job(self, job_id) -> None:
        if job_id is None:
            raise Exception("Invalid param ID parameters.")

In more complex scenarios a validator service or decorators could be used, but the question would be the same: At which point of the code is best practice to validate a user's input.

If the answer is none of the scenarios above (or both), please provide more details on your answer. If possible, try to be language agnostic as I'm looking for a best practice that can be applied anywhere.

Aucun commentaire:

Enregistrer un commentaire