How Do You Validate Models for POST methods?
Hi, I tried a simple example, but it doesn't do the validation and I can post any old JSON to it.
from flask_restx import Namespace, Resource, fields
api = Namespace("kinesis", "Kinesis service for Content Catalog", validate=True)
message_schema = api.model('Message', {
'name': fields.String,
'class': fields.String
})
@api.route("/")
class CatalogKinesisService(Resource):
def get(self):
return {"status": "ok"}
@api.expect(message_schema, validate=True)
def post(self):
# api.payload arrives as anything. Not validated according to message_schema
return {"status": "received", "message":api.payload}
It seems you're missing a required=True on your model fields (if they are required, that is):
message_schema = api.model('Message', {
'name': fields.String(required=True),
'class': fields.String(required=True)
})
Yeah, but this is different than validation. If I define a schema where all the fields are optional. Then validating also means if a field NOT in the schema is provided it should not validate successfully. So the concept of validation and required is different.
I think the validator is parsing leniently by default. I'm not sure how you would disable that...
@radiantone I think you just need to pass strict=True as part of your api.model() call?
Source: https://flask-restx.readthedocs.io/en/latest/_modules/flask_restx/namespace.html#Namespace.model