wyfo / apischema

JSON (de)serialization, GraphQL and JSON schema generation using Python typing.

Home Page:https://wyfo.github.io/apischema/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Check if model can be serialized

justdominator opened this issue · comments

Hi @wyfo ,

I'm looking for a feature with behavior like in the following example:

import typing

class NotSerializableEntity: pass

response_model = typing.List[NotSerializableEntity]

assert can_serialize(response_model)

I need such a feature, or as an alternative, some contract for getting of supported types.

Please, mention if any of these exists or are planned to have. I need this for proper assertion in API endpoints registration.

Thanks :)

is_processable Probably is better naming )

Hopefully, apischema already offers this feature, in a pretty straightforward way.
Take a look at the documentation section about precomputed methods.

Actually, apischema.deserialize/apischema.serialize are just convenient shortcuts of apischema.deserialization_method/apischema.serialization_method.
Checking if a type is serializable can be done by just computing its serialization method:

from apischema import Unsupported, serialization_method

def is_serializable(tp, **kwargs) -> bool:
    try:
        serialization_method(tp, **kwargs)
    except Unsupported:
        return False
    else:
        return True

class NotSerializable:
    pass

assert is_serializable(int)
assert not is_serializable(NotSerializable)

My bad, I have missed this.

Looks exactly what I'm looking for.

Thanks!