How to validate date type in POST payload with flask restplus?
As @andilabs mentions, it really weird to define expected payload twice. You can define expected payload by using only RequestParser
as so:
from flask import Flask, jsonify
from flask_restplus import Api, Resource, fields, reqparse, inputs
app = Flask(__name__)
api = Api(app)
ns = api.namespace('ns')
parser = reqparse.RequestParser()
parser.add_argument('a_str', type=str)
parser.add_argument('a_date', type=inputs.datetime_from_iso8601, required=True)
@ns.route('/')
class AResource(Resource):
@ns.expect(parser)
def get(self):
try: # Will raise an error if date can't be parsed.
args = parser.parse_args() # type `dict`
return jsonify(args)
except: # `a_date` wasn't provided or it failed to parse arguments.
return {}, 400
if __name__ == '__main__':
app.run(debug=True)
Test by using curl
:
$ curl -XGET -H "Content-type: application/json" -d '{"a_str": "Name", "a_date": "2012-01-01"}' 'http://127.0.0.1:5000/ns/'
{
"a_date": "Sun, 01 Jan 2012 00:00:00 GMT",
"a_str": "Name"
}
To validate you can add parameter validate:
@ns.expect(payload, validate=True)
Here is the link to documentation: https://flask-restplus.readthedocs.io/en/stable/swagger.html#the-api-expect-decorator