[PoC] Add support for pydantic models via datamodel-code-generator
#1049
felixatmaltego
started this conversation in
Feature request
Replies: 3 comments 1 reply
|
Yes wondering why the pydantic models are not used by default maybe there's some reason to make it more general purpose. Ran into this when using some endpoints that are pass through and was hoping to reuse the model that was generated. But like you mentioned an option to choose to generate the pydantic models would be great. |
0 replies
|
This was a very helpful post, thanks @felixatmaltego! I found I had to monkey patch the pydantic Otherwise it fails at the line: |
1 reply
|
Seconding this feature, this capability would be a huge help! It would be nice if this was an extra flag that could be passed into the client generation script. |
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.
Hi!
I really like this library and use it for all my clients. Unfortunately, I use
pydanticin myFastAPIprojects. Convertingattrstopydanticmodels is possible, but a bit cumbersome. Instead, I found an easy way to use pydantic models withopenapi-python-client.While
openapi-python-clientgeneratesattrsmodels with custom parser logic, it is nicer for me to usepydanticas in therest of my
FastAPIprojects. Therefore, we generate the models withdatamodel-code-generator, and the client logicwith
openapi-python-client.To make this possible, only two important changes are necessary:
BaseModel::model_validate(...)instead of the customfrom_dict(...)method generatedby
openapi-python-clientfrom ...models.<model-dir> import <Model>tofrom ...models import <Model>,because
datamodel-code-generatorcreates a flat filetemplates/property_templates/model_property.py.jinjatemplates/endpoint_module.py.jinjaTo generate our modified client, we have to:
openapi-client/openapi_client/models/*pydanticmodels toopenapi-client/openapi_client/models/__init__.pyI created a small shell script to do this
The
--strict-nullable --snake-case-field --capitalize-enum-membersflags were necessary to be equivalent to theattrsmodels.Another thing is that
openapi-python-clientsuffixes reserved names with an '_'. I had to change those occurences.Apart from that, the resulting code is compatible with the
attrsmodels.Hope this helps someone. Would be amazing to see this as a feature!
All reactions