Search code examples
validationflaskswaggerdocumentation

How to validate parameters in Flask


Is there a way to validate a sting in Flask to check for the following. I am looking for it to not only show up in the Swagger documentation but to also catch it as a string validation error if possible

  1. Min length 10
  2. Max length 1,024
  3. Starts with [a-zA-Z]
  4. Contains [a-zA-Z0-9=!@#$%^&*()-]
  5. Ends with [a-zA-z0-9]

Here is how I have my endpoint set up so far

from flask import Flask
from flask_restplus import Api, Resource, fields

flask_app= Flask (__name__)
app = Api(app = flask_app,
          version = "1.0",
          title = "Test API",
          description = "Example endpoint to test validation of POST body parameter using Flaskplus")

model = app.model (
    'username model',
    {
        'username': fields.String (
            required = True,
            description = "Username of the user",
            help = "Username cannot be blank, must be of length 10, can start with an upper or lower case letter, can contain upper/lower case, numbers, and the following special characters [=!@#$%^&*()-], and must end with an upper/lower case letter or a number",
            example = "john.smith123"
        )
    }
)

name_space = app.namespace ('', 'Main API')
@name_space.route ("/test")
class test (Resource)

    @app.doc(
        responses = {
            200: 'OK',
            400: 'Invalid Argument',
            500: 'Mapping Key Error'
        }
    )

    @app.expect (model)

    def post (self):
        try:
            username = request.json.get('username')


            return {
                'status': 'Username valid',
                'status_code': 200
            }
        except KeyError as e:
            name_space.abort (
            500,
            e.__doc__,
            status = "Key error",
            statusCode = "500"
            )

Solution

  • You can use the flask-parameter-validation project in order to do this. You'll be able to implement it with something similar to the following:

    from flask_parameter_validation import ValidateParameters, Json
    
    @name_space.route("/test", methods=["POST"])
    @ValidateParameters()
    def hello(
            username: str = Json(
                min_str_length=10,
                max_str_length=1024,
                pattern=r"REGEX"
            )
         ):
        return f"Hello, {username}"
    

    You'll need to replace REGEX with a regex pattern that fulfills your start, middle and end criteria.

    Hope that this helps!