-
Hello, I have an API that returns different JSON structure according to whether an operation was successful or failed. I am wrapping the API in a command line tool and I would like to handle deserialization with uplink and not raise exceptions but simply print the error message returned. Here is a quick excerpt of what it looks like currently: class Success(BaseModel):
code: conint(200, 299)
message: str
class Failure(BaseModel):
errors: Dict
def verbose_response(resp):
...
if "errors" in resp.content:
print("Error handling")
return resp
@response_handler(verbose_response)
class MyApi(Consumer):
@post("/resource")
def create_resource(self, **Body(type=MyPayload) -> Union[Success, Failure]:
... Unfortunately, this raises with |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
One thing I thought was to merge the two classes in one but what bothers me is that the fields are disjoint so I would have to make everything optional. Maybe https://pydantic-docs.helpmanual.io/usage/models/#generic-models is what I'm looking for. |
Beta Was this translation helpful? Give feedback.
-
I think that it can work if you set a Pydantic model using root: https://pydantic-docs.helpmanual.io/usage/models/#custom-root-types something like: class Success(BaseModel):
code: conint(200, 299)
message: str
class Failure(BaseModel):
errors: Dict
class Response(BaseModel):
__root__: Union[Success, Failure] Didn't try this though... |
Beta Was this translation helpful? Give feedback.
One thing I thought was to merge the two classes in one but what bothers me is that the fields are disjoint so I would have to make everything optional. Maybe https://pydantic-docs.helpmanual.io/usage/models/#generic-models is what I'm looking for.