Skip to content
Danila Ganchar edited this page Jan 5, 2024 · 39 revisions

How to use

⚠️ All examples are using @app.errorhandler + demo_error_formatter. Demo is just a demo - demo_error_formatter isn't supported ⚠️

Param description:

Param(
   name: the name of the request parameter
   param_type: where stored param(GET, FORM, JSON, PATH, HEADER)
   value_type: str, bool, int, float, dict, list - which type we want to have
   required: a bool that indicates whether a value is required, True by default
   default: the default value, None by default. You can use lambda for this arg - default=lambda: ['test']
   rule: the list of rules (see Rule class)
)

Note!(you can see the example below)

  • bool should be sent from client as: 1, 0, or true / false in any register
  • list should be sent from client as value1,value2,value3
  • dict should be sent from client as key1:val1,key2:val2

Example:

from flask import Flask, jsonify

from flask_request_validator import *
from flask_request_validator.error_formatter import demo_error_formatter
from flask_request_validator.exceptions import InvalidRequestError

app = Flask(__name__)
@app.errorhandler(InvalidRequestError)
def data_error(e):
    # customize error messages as you wish
    # Attention! Demo is just a demo - demo_error_formatter isn't supported
    return jsonify(demo_error_formatter(e))

@app.route('/json/<string:uid>', methods=['POST'])
@validate_params(
    Param('colors', GET, list),
    Param('values', GET, dict),
    Param('uid', PATH, str, rules=CompositeRule(MinLength(3), MaxLength(5))),
    Param('dt', JSON, str, rules=[Datetime('%Y-%m-%d %H:%M:%S')]),
    Param('status', JSON, str, rules=[Enum('active', 'inactive')]),
    Param('name', JSON, str, rules=[Pattern(r'^[a-z]{4,20}$')]),
)
def json(valid: ValidRequest, uid):
    json_data = valid.get_json()
    json_data['dt'] = json_data['dt'].strftime('%Y-%m-%d')
    return jsonify({
        'get': valid.get_params(),
        'json': json_data,
        'path': valid.get_path_params(),
        'flask_url': valid.get_flask_request().url,
    })

🔴 Incorrect request:

# incorrect request
curl -H "Content-Type: application/json" \                                                                                                                                                                         
     --request POST --data '{}' \
     'http://localhost:5000/json/very_long?colors=green,yellow,blue&values=field1:val1,field2:val2'

# errors
[
  {
    "errors": {
      "dt": "value is required",
      "name": "value is required",
      "status": "value is required"
    },
    "message": "invalid JSON parameters"
  },
  {
    "errors": {
      "uid": "invalid length, max length = 5"
    },
    "message": "invalid PATH parameters"
  }
]

🟢 Correct request:

curl -H "Content-Type: application/json" \
     --request POST \
     -d '{"name":"test","status":"active","dt":"2020-01-02 03:04:05"}' \
     'http://localhost:5000/json/good?colors=green,yellow,blue&values=field1:val1,field2:val2'

# response
{
  "flask_url": "http://localhost:5000/json/good?colors=green,yellow,blue&values=field1:val1,field2:val2",
  "get": {
    "colors": [
      "green",
      "yellow",
      "blue"
    ],
    "values": {
      "field1": "val1",
      "field2": "val2"
    }
  },
  "json": {
    "dt": "2020-01-02",
    "name": "test",
    "status": "active"
  },
  "path": {
    "uid": "good"
  }
}

Additional Information

JFYI: you can move the parameters somewhere(just an example):

# route_params.user
USER_PARAMS = [
    Param('name', JSON, str, rules=[Pattern(r'^[a-z]{4,20}$')]),
    # ... other params
]
# in routes:
from routes_params.user import USER_PARAMS 

@app.route('/json/<string:uid>', methods=['POST'])
@validate_params(*USER_PARAMS)
def json(valid: ValidRequest, uid):
    # ...
Clone this wiki locally