Issue
This is a POST payload body received in backend for store and order generated in a test frontend application that includes 2 keys with objects List and a Object
{
"orderedItems": [
{
"id": 1,
"name": "Asado",
"amount": 2,
"price": 15.99
},
{
"id": 3,
"name": "Sushi",
"amount": 1,
"price": 22.99
},
{
"id": 6,
"name": "Green Bowl",
"amount": 1,
"price": 18.99
}
],
"user": {
"city": "Guatemala",
"email": "[email protected]",
"name": "danny"
}
}
Once is received I tried to validate in Marshmallow with OrderSchema
nested Schema
from marshmallow import validate, validates, validates_schema, \
ValidationError, post_dump, validates
from api import ma
class MealsOrderSchema(ma.Schema):
id= ma.Integer(required=True)
amount= ma.Integer(required=True)
price= ma.Float()
name= ma.String()
class UserDataSchema(ma.Schema):
name= ma.String(required=True)
email= ma.String(required=True, validate=[validate.Email()])
city= ma.String()
class OrderSchema(ma.Schema):
orderedItems= ma.Nested(MealsOrderSchema(many=True))
userData= ma.Nested(UserDataSchema)
Validation is not pass for Object List or object neither, I checked in similar question or other blogs for workaround
{
"code": 400,
"description": "The server found one or more errors in the information that you sent.",
"errors": {
"json": {
"orderedItems": [
"Unknown field."
],
"user": [
"Unknown field."
]
}
},
"message": "Validation Error"
}
Appreciate your hints, thanks
Solution
If you need to manage a list of objects you must use the List
class.
While if the json field name is different from the property name in python, you have to specify which field to load via the attribute
parameter
from marshmallow import Schema, fields
class OrderSchema(Schema):
orderedItems: fields.List(fields.Nested(MealsOrderSchema))
userData: fields.Nested(UserDataSchema, attribute='user')
Answered By - Matteo Pasini
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.