flask-restx icon indicating copy to clipboard operation
flask-restx copied to clipboard

How Do You Validate Models for POST methods?

Open radiantone opened this issue 3 years ago • 4 comments

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}

radiantone avatar May 18 '22 14:05 radiantone

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)
})

sillydan1 avatar May 23 '22 05:05 sillydan1

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.

radiantone avatar May 23 '22 06:05 radiantone

I think the validator is parsing leniently by default. I'm not sure how you would disable that...

sillydan1 avatar May 23 '22 14:05 sillydan1

@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

peter-doggart avatar Jul 08 '22 14:07 peter-doggart