OpenAPITools / openapi-generator

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
https://openapi-generator.tech
Apache License 2.0
20.73k stars 6.32k forks source link

[REQ] Feature Request: Shared type between GET and POST methods instead of eg. GetFoo*Response and CreateFoo*Response #18763

Open javac9 opened 1 month ago

javac9 commented 1 month ago

Is your feature request related to a problem? Please describe.

I'm using server-side JAXRS-SPEC generator (7.6.0)

Let's consider some example endpoint, involving a base class Foo with two children Bar and Baz:

...
"paths": {
  ...
  "/foo/{id}": {
    "get": {
      "operationId": "getFoo",
      ...
      "responses": {
        "default": {
          "content": {
            "application/json": {
              "schema": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/Bar"
                  },
                  {
                    "$ref": "#/components/schemas/Baz"
                  }
                ],
                "discriminator": {
                  "propertyName": "@type"
                }
              }
            }
          }
        }
      }
    },
    "post": {
      "operationId": "createFoo",
      ...
      "requestBody": {
        "required": true,
        "content": {
          "application/json": {
            "schema": {
              "oneOf": [
                {
                  "$ref": "#/components/schemas/Bar"
                },
                {
                  "$ref": "#/components/schemas/Baz"
                }
              ],
              "discriminator": {
                "propertyName": "@type"
              }
            }
          }
        }
      },
...

Since the GET method might return an object either of type Bar or Baz, the generated return type named GetFooDefaultResponse contains all attributes of the parent and both (sub)type classes from which one can extract appropriate attributes for desired type.

Now, for the POST method, the requestBody is specified in a way that completely corresponds to the default response of the GET above, so it gets generated like this:

  @Override
  public CreateFooDefaultResponse createFoo(String id, GetFooDefaultResponse getFooDefaultResponse) {
      return ....;
  }

I find this problematic for several reasons:

Describe the solution you'd like

A solution to the problem might be some of the following:

Describe alternatives you've considered

jpfinne commented 1 month ago

You can create a shared model like OneOfBarBaz and $ref it under schema. Or you can use one of the mapping described in https://openapi-generator.tech/docs/customization/ Probably type-mappings or schema-mapppings (typeMappings/schemaMappings in the maven plugin) You might want to use the verbose option to know the name used internally