Reputation: 323
I'm using openapi-generator-cli to generate Python clients, and it's working great except for a specific scenario. I need to send requests to an external service where all nullable fields must be included even if their values are None. When I generate the client with openapi-generator-cli, it creates models with a to_dict method like this:
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
Is there a way to configure openapi-generator-cli to allow including None values for nullable fields in the to_dict method? This will be accomplished if exclude_none=False
but I don't find any directive for openapi-generator for this.
Let's say I have a Python dictionary like this:
request_data = {
"account": None,
"lastName": "Doe",
"firstName": "Jon",
"middleInitial": None,
"companyName": None,
"isOrganization": False,
"address": {
"type": "P",
"address1": "5171 California Avenue",
"address2": "Suite 200",
"address3": None,
"address4": None,
"locality": "Irvine",
"region": "CA",
"postalCode": "92617",
"countryCode": "US"
}
}
In this example, even though some fields like "account", "middleInitial", and "companyName" are None, I need them to be included in the request sent to the external service.
Additional Note:
Perhaps the issue lies not in the configuration of openapi-generator but in the Swagger file used to create these models. However, I couldn't find any configuration in the Swagger file that results in the desired models. Here's a snippet of my Swagger models:
User:
type: object
required:
- address
properties:
account:
type: string
default: null
middleInitial:
type: string
default: null
lastName:
type: string
default: null
firstName:
type: string
default: null
companyName:
type: string
default: null
isOrganization:
type: boolean
default: null
address:
$ref: "#/components/schemas/Adress"
Upvotes: 1
Views: 815
Reputation: 323
I found a solution on this one. I used a mustache template overriding the same template on the docker cli.
docker run --rm \
-v ${PWD}:/local openapitools/openapi-generator-cli:latest-release generate \
--input-spec https://api.swaggerhub.com/apis/supercoolapi/$API_VERSION?resolved=true \
--auth "Authorization: ${SWAGGER_API_TOKEN}" \
--generator-name python \
--output /local \
--additional-properties=packageVersion=$PACKAGE_VERSION,packageName=$PACKAGE_NAME,library=asyncio \
--template-dir /local/templates
I used this template and overwritted how to_dict method is created.
Upvotes: 1