Search code examples
pythongetguzzleflask-restful

Regex in RequestParser for Python Flask-RESTful


Wondering if it's possible in Python Flask-RESTful, to use regular expressions while parsing arguments?

For example, per the documentation for multiple values, I have the following argument I'm expecting in our API:

parser.add_argument('fq', type=str, action='append', help='expecting filter query (fq) (multiple)')

As is evident in the description and parameters, this field can repeat. Unfortunately, I'm working with PHP libraries (namely, http_build_query via Guzzle) that return repeating values in the following form:

?fq[0]=foo&fq[1]=bar&fq[2]=baz

With an unknown number of fq parameters to parse, it would be invaluable to be able to define a regex parser, something akin to:

parser.add_argument('(fq)\[[0-9]+\]', type=str, action='append', help='expecting filter query (fq) (multiple)')

that would capture anything in the form fq[#], drop the brackted [] suffix, and append all those to an fq list in the args dictionary.

Is that possible with Flask-RESTful? I'm not seeing anything in the documentation, save some comments about potentially moving to something like Marshmallow.


Solution

  • You can use following code to check input for regex:

    from flask_restful import inputs
    ...
    .....
    parser.add_argument('fq', type=inputs.regex('^[0-9]+$'), action='append', help='expecting filter query (fq) (multiple)')