Skip to content

[BUG] OpenAPI 4.0.2 not able to generate anyOf models. #4576

Open

Description

@charmygarg
Description

I have created a swagger file openapi: 3.0.0 having Account and Contact as references in anyOf something like this:

anyOf:
              - $ref: "#/components/schemas/Account"
              - $ref: "#/components/schemas/Contact"
openapi-generator version

4.0.2

Steps to reproduce

After running mvn generate-sources command swagger generates models in /target folder. The issue here is that swagger is not able to generate class AnyOfAccountContact which it should be.

The error looks like this:
error

Activity

  1. changed the title [-][BUG] OpenAPI 4.0.2 not able to generating anyOf models.[/-] [+][BUG] OpenAPI 4.0.2 not able to generate anyOf models.[/+] on Nov 22, 2019
  2. macjohnny commented on Nov 22, 2019

    @macjohnny
    Member

    have you tried the latest version?

  3. Devilsmaul commented on Feb 3, 2020

    @Devilsmaul

    yes the problem still exists with version 4.2.3
    The anyOf.... model classes are not generated at all.
    Maybe the length of the path together with the model name is longer then allowed and the file can not be created?

  4. conet commented on Apr 3, 2020

    @conet

    I'm also seeing this in 4.2.3.

  5. jamesmfriedman commented on Jun 25, 2020

    @jamesmfriedman

    I'm seeing this in the latest using the typescript-fetch generator.

    It improperly returns invalid javascript that points to a class, a typescript single pipe, and a function that isn't actually defined.

    'item': Item | numberToJSON(value.itemId),
    
  6. rvsingh011 commented on Jul 24, 2020

    @rvsingh011

    I am also getting inappropriate model generated for anyOf in golang generators,

    // Schematics location where action data will be saved and jobs executed
    	Location AnyOfServerLocation `json:"location,omitempty"`
    

    It is generated like this. Any fix for this?

  7. black-snow commented on Sep 17, 2020

    @black-snow

    Still seeing this in 5.0.0-beta2 - will #7263 fix this?

  8. DenisButCheR commented on Nov 24, 2020

    @DenisButCheR

    I have the same issue. Generating for Javascript. AnyOf file which is required in the model just doesn't exist. Looks like the generator does not generate it. No errors and warnings during the generation process.

    5.0.0-beta3
    

    Doesn't solves the problem

  9. joshaq commented on Mar 17, 2021

    @joshaq

    I stumbled on the same bug and built a minimal reproduction before I found this issue. I am using 5.0.0.

    OpenAPI spec:

    openapi: 3.0.2
    info:
      title: Test
      version: 0.1.0
    paths:
      /path-with-anyof-body:
        get:
          responses:
            '200':
              description: description
              content:
                application/json:
                  schema:
                    anyOf:
                      -
                        "$ref": "#/components/schemas/Obj1"
                      -
                        "$ref": "#/components/schemas/Obj2"
    components:
      schemas:
        Obj1:
          type: object
          properties:
            foo:
              type: string
        Obj2:
          type: object
          properties:
            bar:
              type: number
    
    $ openapi-generator-cli version
    5.0.0
    
    $ openapi-generator-cli generate -i ./openapi.json -g typescript-fetch -o testout --additional-properties=typescriptThreePlus=true
    
    $ cat testout/apis/DefaultApi.ts 
    /* tslint:disable */
    /* eslint-disable */
    /**
     * Test
     * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
     *
     * The version of the OpenAPI document: 0.1.0
     * 
     *
     * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
     * https://openapi-generator.tech
     * Do not edit the class manually.
     */
    
    
    import * as runtime from '../runtime';
    import {
        Obj1,
        Obj1FromJSON,
        Obj1ToJSON,
        Obj2,
        Obj2FromJSON,
        Obj2ToJSON,
    } from '../models';
    
    /**
     * 
     */
    export class DefaultApi extends runtime.BaseAPI {
    
        /**
         */
        async pathWithAnyofBodyGetRaw(): Promise<runtime.ApiResponse<Obj1 | Obj2>> {
            const queryParameters: any = {};
    
            const headerParameters: runtime.HTTPHeaders = {};
    
            const response = await this.request({
                path: `/path-with-anyof-body`,
                method: 'GET',
                headers: headerParameters,
                query: queryParameters,
            });
    
            return new runtime.JSONApiResponse(response, (jsonValue) => Obj1 | Obj2FromJSON(jsonValue));
        }
    
        /**
         */
        async pathWithAnyofBodyGet(): Promise<Obj1 | Obj2> {
            const response = await this.pathWithAnyofBodyGetRaw();
            return await response.value();
        }
    
    }
    
  10. wing328 commented on Mar 17, 2021

    @wing328
    Member

    We've implemented oneOf, anyOf support in other generators such as Java, C#, Python, PowerShell, Go, Ruby and more.

    If anyone has time to help with the implementation of oneOf/anyOf in the typescript generator, I can work with you to show you some good starting points and generate some files so that you can fill in the blanks (implementation details).

  11. added
    Inline Schema HandlingSchema contains a complex schema in items/additionalProperties/allOf/oneOf/anyOf
    on Mar 30, 2021
  12. Dennis-Nilsson commented on Mar 31, 2021

    @Dennis-Nilsson

    We've implemented oneOf, anyOf support in other generators such as Java, C#, Python, PowerShell, Go, Ruby and more.

    @wing328
    Great job! In which version and when will it be released? (openapi-generator-maven-plugin)

  13. wing328 commented on Apr 30, 2021

    @wing328
    Member

    @DennisNilssonB3 please try 5.1.0 or the latest stable version

  14. mimkorn commented on Jun 30, 2021

    @mimkorn

    Same here, anyOf is not generating the necessary class when using spring generator spring-cloud library.

    Using latest generator, also tested on 6.0.0 latest snapshot and 5.2 latest snapshot just now.

    Using this schema

        Error:
          type: object
          example:
            timestamp: '2021-05-19T16:56:04.969+00:00'
            status: 409
            error: Conflict
            message: Application already exits
            path: /public/subscriptions
          properties:
            timestamp:
              type: string
              format: date-time
            status:
              type: integer
            error:
              type: string
            message:
              type: string
            debugMessage:
              type: string
            path:
              type: string
            errors:
              type: array
              items:
                anyOf:
                  - $ref: '#/components/schemas/ValidationError'
        ValidationError:
          title: ValidationError
          type: object
          description: ''
          properties:
            object:
              type: string
            field:
              type: string
            rejectedValue:
              type: object
            message:
              type: string

    and this configuration of the maven plugin:

    <plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>5.1.0</version>
    <executions>
    	<execution>
    		<id>Java Spring server stub generation</id>
    		<goals>
    			<goal>generate</goal>
    		</goals>
    		<configuration>
    			<inputSpec>${project.basedir}/openapi/subscription.yaml</inputSpec>
    			<generatorName>spring</generatorName>
    
    			<generateApis>true</generateApis>
    			<generateModels>true</generateModels>
    			<generateModelDocumentation>false</generateModelDocumentation>
    			<generateModelTests>false</generateModelTests>
    			<generateSupportingFiles>true</generateSupportingFiles>
    
    			<configOptions>
    				<unhandledException>true</unhandledException>
    				<library>spring-cloud</library>
    				<openApiNullable>false</openApiNullable>
    				<dateLibrary>java8</dateLibrary>
    			</configOptions>
    			<output>${project.build.directory}/generated-sources/java-server</output>
    		</configuration>
    	</execution>
    </executions>
    </plugin>
  15. 1 remaining item

  16. iyakobson commented on Oct 1, 2021

    @iyakobson

    @DennisNilssonB3 please try 5.1.0 or the latest stable version

    I've tried 5.2.1 version for generation java server (as well as swagger-codegen) - it generates interface with name AnyOfobjectobjectobjectб but no realisation for this interface :-((((

    @wing328 should i use some options during generation or to do something else?

    i tried simple way - "openapi-generator-cli generate -g java"

  17. gbvanrenswoude commented on Oct 27, 2021

    @gbvanrenswoude

    @sauravInfoObject did you get a fix working yet? Could you share it, if so? Thanks a lot :)

  18. nrbw commented on Dec 16, 2021

    @nrbw

    I just encountered the same problem today with openapi-generator-maven-plugin version 5.3.0 for generating java with resttemplate library.

  19. Jwely commented on Mar 25, 2022

    @Jwely

    Same bug persists when generating java client with version 5.4

  20. bremme commented on Mar 29, 2022

    @bremme

    I'm running into the same issues using the Gradle plugin version 5.4.0 and the spring server generator. Anybody found a workaround for this issues perhaps?

  21. sweetmadhu commented on Mar 30, 2022

    @sweetmadhu

    @wing328 Any ETA by which the issue will be fixed?

  22. CyberSteve738 commented on Apr 15, 2022

    @CyberSteve738

    the issue is happening for me while attempting to generate the openapi spec for Alpaca api, specifically for a java client using the resttemplate library

  23. Shryne commented on Apr 27, 2022

    @Shryne

    Happens to me with 6.0.0-beta with java...

  24. macjohnny commented on Apr 27, 2022

    @macjohnny
    Member

    Everyone is welcome to implement a fix

  25. Embraser01 commented on Apr 27, 2022

    @Embraser01

    I'm running into the same issues using the Gradle plugin version 5.4.0 and the spring server generator. Anybody found a workaround for this issues perhaps?

    After stumbling on this issue last year, I decided to create a new generator that would generate complex types (inline or not). It has been working great for me, you can find it here: https://github.com/Embraser01/typoas
    Edit: It only applies to TS/JS clients, not other languages

    P.S.: The main goal here isn't to advertise my project, just to propose a solution to this issue. If wanted, I can remove the link to the project and let users find it through my profile

  26. wing328 commented on Apr 27, 2022

    @wing328
    Member

    specifically for a java client using the resttemplate library

    resttempalte doesnt' support anyOf/oneOf yet.

    Only okhttp-gson, jersey2 and native supports anyOf/oneOf.

    We welcome PRs to plot the implementation of anyOf/oneOf to resttemplate or other libraries supported by the java client generator.

  27. CyberSteve738 commented on Apr 28, 2022

    @CyberSteve738

    I really appreciate the response @wing328 ! was just looking to be pointed in the right direction. I will use one of the other libraries!

  28. uri200 commented on Jul 19, 2022

    @uri200

    Hey @wing328 just in case to inform other people using go. AnyOf or oneOf is not fully working.
    For example

    java openapi-generator-cli-6.0.0.jar generate -i https://raw.githubusercontent.com/jdegre/5GC_APIs/master/TS29522_TrafficInfluence.yaml -g go-server -o ./server_trafficInfluence
    
    

    The result is the schema seems to generate but it looks like it is limited to the first element of the allOf or anyOff

    [main] WARN  o.o.codegen.DefaultCodegen - allOf with multiple schemas defined. Using only the first one: AnyType
    

    Also we get some errors when producing anyOf or allOf or oneOf elements #12920

  29. wing328 commented on Jun 20, 2023

    @wing328
    Member

    @uri200 can you please give it another try in the latest master or stable version v6.6.0?

    I think it should be resolved.

  30. ysulyma commented on Jul 27, 2023

    @ysulyma

    @wing328 I'm encountering a similar issue with the Go generator. The schema

    openapi: 3.0.2
    info:
      title: Minimal repro of anyOf bug
      version: 1.0.0
    servers:
      - url: http://localhost:8080/api/v1
        description: Development server
    paths:
      /:
        get:
          responses:
            201:
              description: Filler
    components:
      schemas:
        Model:
          type: object
          required:
            - value
          properties:
            value:
              anyOf:
                - type: number
                - type: string
                - type: array
                  items:
                    type: string
                - type: array
                  items:
                    type: number

    run with

    openapi-generator generate \
      -i ./schema.yaml \
      -g go \
      -o entity \
      --global-property models,supportingFiles=utils.go,modelDocs=false \
      --additional-properties enumClassPrefix=true,packageName=entity

    produces

    type ModelValue struct {
    	[]float32 *[]float32
    	[]string *[]string
    	float32 *float32
    	string *string
    }

    which is invalid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Inline Schema HandlingSchema contains a complex schema in items/additionalProperties/allOf/oneOf/anyOfIssue: Bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions