Invalid code generated for missing discriminator property, but validation passes
Description
A spec with missing discriminator property passes validation, but generates invalid (Java) code.
openapi-generator version
3.3.0-SNAPSHOT
OpenAPI declaration file content or url
{
"openapi": "3.0.0",
"info": {
"description": "blah",
"version": "1.0.0",
"title": "blah"
},
"paths": {
"/test": {
"post": {
"tags": [
"test"
],
"operationId": "testOp",
"responses": {
"405": {
"description": "Invalid input"
}
},
"requestBody": {
"$ref": "#/components/requestBodies/Test"
}
}
}
},
"components": {
"requestBodies": {
"Test": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Test"
}
}
}
}
},
"schemas": {
"Base": {
"properties": {
"status": {
"type": "string"
}
},
"discriminator":{
"propertyName": "type"
}
},
"Test": {
"allOf":[
{ "$ref": "#/components/schemas/Base" },
{
"type":"object",
"properties": {
"name": {
"type": "string"
}
}
}
]
}
}
}
}
rpdmcpp.config is
{
"declspec" : "DL_GLOBAL_CLASS",
"appName" : "RPDM",
"appDescription" : "RedPoint Data Management services"
}
Command line used for generation
Validate succeeds
java -cp openapi-generator-cli.jar org.openapitools.codegen.OpenAPIGenerator validate -i test2.json
Validating spec (test2.json)
No validation issues detected.
But java code generation:
java -cp openapi-generator-cli.jar org.openapitools.codegen.OpenAPIGenerator generate -v -o genjava -g java -i test2.json -c rpdmcpp.config
produces non-compiling code. The problem is that the type field is not defined. In Base.java:
public Base() {
this.type = this.getClass().getSimpleName();
}
Suggest a fix/enhancement
Validation should flag the spec as being in error.
I'm getting the java.lang.IllegalArgumentException: missing discriminator field error when I run the code of my client (java gson). So I was able to generate the client apparently without issues.
I'm not sure on how to grasp on which line is the error(s). Any help here?
@carlos-mg89 please share the spec to reproduce the issue.
I have the same issue trying to generate code for https://developers.strava.com/swagger/swagger.json
java.lang.IllegalArgumentException: missing discriminator field: <>
at com.strava.api.v3.JSON.getDiscriminatorValue(JSON.java:443)
at com.strava.api.v3.JSON.access$000(JSON.java:43)
at com.strava.api.v3.JSON$20.getClassForElement(JSON.java:115)
at io.gsonfire.gson.TypeSelectorTypeAdapterFactory$TypeSelectorTypeAdapter.read(TypeSelectorTypeAdapterFactory.java:65)
at io.gsonfire.gson.NullableTypeAdapter.read(NullableTypeAdapter.java:36)
at io.gsonfire.gson.HooksTypeAdapter.deserialize(HooksTypeAdapter.java:86)
at io.gsonfire.gson.HooksTypeAdapter.read(HooksTypeAdapter.java:54)
at com.google.gson.Gson.fromJson(Gson.java:932)
at com.google.gson.Gson.fromJson(Gson.java:897)
at com.google.gson.Gson.fromJson(Gson.java:846)
at com.strava.api.v3.JSON.deserialize(JSON.java:517)
at com.strava.api.v3.ApiClient.deserialize(ApiClient.java:710)
at com.strava.api.v3.ApiClient.handleResponse(ApiClient.java:913)
at com.strava.api.v3.ApiClient$1.onResponse(ApiClient.java:879)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:177)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
discriminatorField is just "" (empty string)
Any possible workarounds?
I am seeing the same issue in a java client I generated from editor.swagger.io, namely discriminatorField is an empty string and it throws the missing discriminator field error. This is the YAML and generated code causing the error:
https://raw.githubusercontent.com/Alfresco/rest-api-explorer/6.1.0/src/main/webapp/definitions/alfresco-core.yaml
public Class getClassForElement(JsonElement readElement) {
Map classByDiscriminatorValue = new HashMap();
classByDiscriminatorValue.put("DeletedNode".toUpperCase(), DeletedNode.class);
classByDiscriminatorValue.put("NodeAssociation".toUpperCase(), NodeAssociation.class);
classByDiscriminatorValue.put("NodeChildAssociation".toUpperCase(), NodeChildAssociation.class);
classByDiscriminatorValue.put("Node".toUpperCase(), Node.class);
return getClassByDiscriminator(
classByDiscriminatorValue,
getDiscriminatorValue(readElement, ""));
}
Has anyone been able to resolve this? I've been receiving the same issue.
I'm fairly certain my issue has to do with the allOf keyword. Here is an example of what isn't working
StatusBasicInfo:
allOf:
- $ref: "#/components/schemas/ServerResponse"
- type: object
properties:
basic_info_list:
type: array
items:
$ref: '#/components/schemas/ShipmentBasicInfo'
When i generated the code without extending - $ref: "#/components/schemas/ServerResponse" , I was able to make a successful API call, but now i'm getting the same missing discriminator field: <> as above
I can also confirm with the usage of allOf with a java generated (tested with okhttp-gsjon) client does not work. The only workaround is to get rid of allOf. Kinda sad because this makes enables re-use. Now I have many unnecessary duplications.
same problem here
Same issue here (io.swagger.codegen.v3.swagger-codegen-maven-plugin 3.0.19). Worked using a verbose YAML file, but failed when using allOf with discriminatorField being a blank string.
YMMV but I was able to get around this by switching to the 'resttemplate' library as a config option:
<plugin>
<groupId>io.swagger.codegen.v3</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>${io.swagger.swagger-codegen-maven-plugin}</version>
<executions>
<execution>
<id>Build Java Client API</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${project.build.directory}/maven-shared-archive-resources/swagger-templates/swagger.yaml</inputSpec>
<language>java</language>
<generateApiTests>false</generateApiTests>
<generateApiDocumentation>false</generateApiDocumentation>
<generateModelTests>false</generateModelTests>
<generateModelDocumentation>false</generateModelDocumentation>
<output>target/generated-sources/swagger</output>
<apiPackage>com.example.api</apiPackage>
<modelPackage>com.example.model</modelPackage>
<artifactId>client</artifactId>
<groupId>com.example</groupId>
<artifactVersion>${project.version}</artifactVersion>
<environmentVariables>
<models/>
<apis/>
<supportingFiles />
</environmentVariables>
<configOptions>
<dateLibrary>java8</dateLibrary>
<library>resttemplate</library>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
The codegen now outputs a functional client with allOf still used in the YAML.
Same issue trying to generate client code from https://developers.strava.com/swagger/swagger.json
@Ludde321 , did you manage to resolve that somehow?
My temporary solution for java client generated from editor.swagger.io: go to JSON class
//.....
.registerTypeSelector(TagFields.class, new TypeSelector() {
@Override
public Class getClassForElement(JsonElement readElement) {
Map classByDiscriminatorValue = new HashMap();
classByDiscriminatorValue.put("TagCreateRequest".toUpperCase(), TagCreateRequest.class);
classByDiscriminatorValue.put("TagUpdateRequest".toUpperCase(), TagUpdateRequest.class);
classByDiscriminatorValue.put("TagFields".toUpperCase(), TagFields.class);
return getClassByDiscriminator(
classByDiscriminatorValue, //change this String
getDiscriminatorValue(readElement, "TagFields"));
}
// change this method body
private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) {
return discriminatorField;
}
private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) {
Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue.toUpperCase());
if(null == clazz) {
throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">");
}
return clazz;
}
but it's a dirty terrible hack
Hi @owpk! I'm only using swagger-codegen generated client for testing so that's okay for me as temporary workaround. Thanks!
Same here. Workaround seems to be waaay too hacky for production use.
Upvote - I'd need this for production