Search code examples
pythonpython-3.xflaskjson-schema-validatormarshmallow

How to raise an exception if json parameter is not having value (empty string)?


I want to raise an exception if my input json will look like :

{
"username":"user",
"password": ""
}

if i am passing password as null then i want to raise an exception . May i know how does it handle by marshmallow . I dont want to check explicitly like below :

request_jsn = request.get_json()
if 'password' in request_jsn.keys() :
   if request_jsn['password'] :
     password = request_jsn['password']
from marshmallow import Schema, fields
class UserSchema(Schema):
username = fields.String(required=True)
password = fields.String(required=True)
--------------
def post(self):

    if not request.json:
        return jsonify( {'msg':"Unsupported media type,Requests must be JSON",'code': 415})
    try:
       request_jsn =  Schema().load(request.get_json())
    except ValidationError as e:
        return jsonify(error_dict(current_request_id(), str(e), 400))

Solution

  • I got the way to work with it.

    username = fields.String(required=True, validate=validate.Length(min=1, error="Field should not be empty.")) 
    password = fields.String(required=True, validate=validate.Length(min=1, error="Field should not be empty.")