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
21.49k stars 6.51k forks source link

Question: [Java] How to customise Base-class if oneOf is used as request body #18842

Open arandth opened 4 months ago

arandth commented 4 months ago

My API spec uses oneOf when specifying the schema for a request body similar to the following:

  /request-endpoint:
    post:
      requestBody:
        content:
          application/json
            schema:
              oneOf:
                - $ref: '#/components/schemas/RequestA'
                - $ref: '#/components/schemas/RequestB'

Of course there are two schema definitions for these reqeust types.

The generator generates a base class for these types, and they are derived from it. I can customize the name of the base class by using the inlineSchemaNameMappings option (thow it is a bit tricky to find out the correct source to use):

<inlineSchemaNameMappings>
                                _request_endpoint_post_request=RequestBase
</inlineSchemaNameMappings>

The problem is that in order to correctly parse the request-body, the RequestBase interface needs some special annotations:

@Valid
@JsonTypeInfo(use = DEDUCTION)
@JsonSubTypes({ @Type(RequestA.class), @Type(RequestB.class) })

So the question is: is openapi-generator able to generate these annotations? (I only know the approach with "discriminator", but this is not usable in my case.)

It would also be a sufficient to not generate the RequestBase class using something like "schemaMapping" (which would work for RequestA and/or RequestB), but I didn't get it to work for RequestBase.

Thanks for any help.

openapi-generator version

openapi-maven-plugin 7.6.0

arandth commented 2 months ago

Hi community, any ideas here? Thanks, Thomas

bergac commented 4 days ago

Is it possible that you can write your own interface class? If so, you can put the correct annotations in there, and use the x-implements property in RequestA and RequestB.

E.g.:

com.some.package

@Valid
@JsonTypeInfo(use = DEDUCTION)
@JsonSubTypes({ @Type(RequestA.class), @Type(RequestB.class) })
public interface RequestBase {}

And in your api specification:

...

components:
  schemas:
    RequestA:
      x-implements: com.some.package.RequestBase
      ...
    RequestB:
      x-implements: com.some.package.RequestBase
      ...