3

There is a nested rule of class DocumentSchema in pydantic written in FastApi as follows:

class DocumentSchema(BaseModel):
    clientName: str
    transactionId: str
    documentList: List[SingleDocumentSchema]

and

class SingleDocumentSchema(BaseModel):
    documentInfo: DocumentInfoSchema
    articleList: List[DocumentArticleSchema]

and

class DocumentInfoSchema(BaseModel):
    title: str
    type: str
    referenceId: int
    batchNoList: Optional[List]
    otherData: Optional[Json]

and

class DocumentArticleSchema(BaseModel):
    type: str
    value: int
    accountType: Optional[AccountTypeEnums]
    accountId: Optional[int]
    otherData: Optional[Json]

and this is the snippets of python code which receives the message from Kafka and process it:

def process(self) -> bool:
    try:
        DocumentSchema(
            **json.loads(self._message)
        )
        return self._process()

    except ValidationError as e:
        raise UnprocessableEntityException(e, self._topic)
    except ValueError as e:
        raise UnprocessableEntityException(e, self._topic)
    except Exception as e:
        raise UnprocessableEntityException(e, self._topic) 

but for input

{
    "clientName": "amazon",
    "transactionId": "e3e60ca3-7eb1-4a55-ae35-c43f9b2ea3fd",
    "documentList": [
        {
            "documentInfo": {
                "title": "New Order",
                "type": "order",
                "referenceId": 19488682
            },
            "articleList": [
                {
                    "type": "product_price",
                    "value": 1350,
                    "otherData": {
                        "weight": "4 kg"
                    }
                }
            ]
        }
    ]
}

It reports the validation error

{"message":"1 validation error for DocumentSchema\ndocumentList -> 0 -> articleList -> 0 -> otherData\n JSON object must be str, bytes or bytearray (type=type_error.json)"}

I should mention that without OtherData everything is Ok.

I don't know how to fix it.

Thanks in advance.

2 Answers 2

6

The error occurs because the Json type expects to get a JSON string to deserialize (either as str, bytes or bytearray) to the actual data type.

Since you have already deserialized the string to a dictionary, you could set it as an Optional[Dict] - i.e. either empty or as a list of key: value pairs which should match what you've added as an example.

Sign up to request clarification or add additional context in comments.

Comments

0

Pydantic error object have json attribute,

errors.json()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.