Replies: 2 comments 1 reply
-
I also tried using the from pydantic import BaseModel, RootModel
class Body(BaseModel):
user_id: int
message: str
OneOrManyMessages = RootModel[Body | list[Body]]
@app.post("/message")
def send_message(body: OneOrManyMessages):
...
Digging into it a little more, I can't quite see what the issue is; my guess is the validation being done can't handle it In [1]: from flask_openapi3.utils import get_model_schema
In [2]: from pydantic import BaseModel, RootModel
...:
...: class Body(BaseModel):
...: user_id: int
...: message: str
...:
...: OneOrManyMessages = RootModel[Body | list[Body]]
In [3]: get_model_schema(OneOrManyMessages)
Out[3]:
{'$defs': {'Body': {'properties': {'user_id': {'title': 'User Id',
'type': 'integer'},
'message': {'title': 'Message', 'type': 'string'}},
'required': ['user_id', 'message'],
'title': 'Body',
'type': 'object'}},
'anyOf': [{'$ref': '#/components/schemas/Body'},
{'items': {'$ref': '#/components/schemas/Body'}, 'type': 'array'}],
'title': 'RootModel[Union[Body, list[Body]]]'}
In [4]: issubclass(OneOrManyMessages, BaseModel)
Out[4]: True
In [5]: import inspect
In [6]: inspect.isclass(OneOrManyMessages)
Out[6]: True
In [7]: type(OneOrManyMessages)
Out[7]: pydantic._internal._model_construction.ModelMetaclass |
Beta Was this translation helpful? Give feedback.
1 reply
-
I recommend a way to write it that meets your needs: class OneOrManyMessages(RootModel):
root: Body | list[Body] |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm currently migrating a project to flask-openapi3, and I'm trying to work out how to correctly setup the
body
to accept either a single item or an array or itemsIf I configure it as the above, I can accept a single payload, but if I change the body definition to this, I get an exception
Can anyone advise how I might be able to accomplish this?
Beta Was this translation helpful? Give feedback.
All reactions