I am trying to use a serializer to store my JSON data into DB. I have created an API and using in postman. Like :
POST endpoint: API/transaction
and data with JSON
format
Where I load into serializer it returns an error. I tested in the shell too. I am not getting an exact error in the debug tool.
my serializer is:
class TransactionSerializer(ma.ModelSchema):
"""transaction validation"""
partner_client_id = fields.String(required=True)
agent_id = fields.String(required=True)
agent_msisdn = fields.String(required=True)
code = fields.Integer(required=True)
title = fields.String(required=False)
price = fields.String(required=True)
currency = fields.String(required=False)
user_msisdn = fields.String(required=True)
requested_ip = fields.String(required=False)
platform = fields.String(required=False)
is_recurring = fields.Boolean(required=False)
class Meta:
"""Meta class."""
model = Transaction
Here is python SHELL
>>> from app.serializer.transaction_serializer import TransactionSerializer
>>> transaction_serializer = TransactionSerializer()
>>> trn_json ={
... "partner_client_id": "CLIENTID009",
... "agent_id": "agent222",
... "agent_msisdn": "8801831803255",
... "code": "10",
... "title": "10 Days Unlimited ",
... "price": "10.00",
... "currency": "BDT",
... "user_msisdn": "8801925533362",
... "requested_ip": "127.0.0.1",
... "platform": "universal",
... "is_recurring": True
... }
>>> trn_json
{'partner_client_id': 'CLIENTID009', 'agent_id': 'agent222', 'agent_msisdn': '8801831803255', 'code': '10', 'title': '10 Days Unlimited ', 'price': '10.00', 'currency': 'BDT', 'user_msisdn': '8801925533362', 'requested_ip': '127.0.0.1', 'platform': 'universal', 'is_recurring': True}
>>> transaction, errors = transaction_serializer.load(trn_json)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'Transaction' object is not iterable
You're trying to unpack the result of the loading as (result, error) tuple. This is what you would do with marshmallow 2.
With marshmallow 3, loading and dumping either output the result (no error) or raise an exception. This is equivalent to marshmallow 2 when the schema has strict=True
meta option. See Upgrading to 3.0 - Schemas are always strict.
My guess is you're using marshmallow 3 (which is great) but the marshmallow 2 way.
Please try
try:
transaction = transaction_serializer.load(trn_json)
except ma.ValidationError as err:
errors = err.messages
valid_data = err.valid_data
If you copied the tuple unpacking code from some documentation, you may want to ping the author for an update.