[PoC] Add support for pydantic
models via datamodel-code-generator
#1049
felixatmaltego
started this conversation in
Feature request
Replies: 2 comments
-
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. |
Beta Was this translation helpful? Give feedback.
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:
|
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
-
Hi!
I really like this library and use it for all my clients. Unfortunately, I use
pydantic
in myFastAPI
projects. Convertingattrs
topydantic
models is possible, but a bit cumbersome. Instead, I found an easy way to use pydantic models withopenapi-python-client
.While
openapi-python-client
generatesattrs
models with custom parser logic, it is nicer for me to usepydantic
as in therest of my
FastAPI
projects. 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-client
from ...models.<model-dir> import <Model>
tofrom ...models import <Model>
,because
datamodel-code-generator
creates a flat filetemplates/property_templates/model_property.py.jinja
templates/endpoint_module.py.jinja
To generate our modified client, we have to:
openapi-client/openapi_client/models/*
pydantic
models toopenapi-client/openapi_client/models/__init__.py
I created a small shell script to do this
The
--strict-nullable --snake-case-field --capitalize-enum-members
flags were necessary to be equivalent to theattrs
models.Another thing is that
openapi-python-client
suffixes reserved names with an '_'. I had to change those occurences.Apart from that, the resulting code is compatible with the
attrs
models.Hope this helps someone. Would be amazing to see this as a feature!
Beta Was this translation helpful? Give feedback.
All reactions