Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
charmygarg opened this issue Nov 22, 2019 · 28 comments
Open

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

charmygarg opened this issue Nov 22, 2019 · 28 comments
Labels
Inline Schema Handling Schema contains a complex schema in items/additionalProperties/allOf/oneOf/anyOf Issue: Bug

Comments

@charmygarg
Copy link

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

@charmygarg charmygarg 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. Nov 22, 2019
@macjohnny
Copy link
Member

have you tried the latest version?

@Devilsmaul
Copy link

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?

@conet
Copy link

conet commented Apr 3, 2020

I'm also seeing this in 4.2.3.

@jamesmfriedman
Copy link

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),

@rvsingh011
Copy link

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?

@black-snow
Copy link

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

@DenisButCheR
Copy link

DenisButCheR commented Nov 24, 2020

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

@joshaq
Copy link

joshaq commented Mar 17, 2021

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();
    }

}

@wing328
Copy link
Member

wing328 commented Mar 17, 2021

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).

@spacether spacether added the Inline Schema Handling Schema contains a complex schema in items/additionalProperties/allOf/oneOf/anyOf label Mar 30, 2021
@Dennis-Nilsson
Copy link

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)

@wing328
Copy link
Member

wing328 commented Apr 30, 2021

@DennisNilssonB3 please try 5.1.0 or the latest stable version

@mimkorn
Copy link

mimkorn commented Jun 30, 2021

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>

@sauravInfoObject
Copy link

sauravInfoObject commented Sep 16, 2021

I am having a similar issue with anyoff in Java and Python. I have tried 5.2.0 as well as 5.2.1 latest stable. The required class is missing in the generated code.

This my swagger def:

`        privacyRestrictions:
          type: object
          nullable: true
          anyOf:
            - $ref: '#/components/schemas/dataDomain'
            - $ref: '#/components/schemas/fieldTypes'
            - $ref: '#/components/schemas/columns'`
  component:
       schemas:
          dataDomain:
             title: DATA_DOMAINS
             type: object
             properties:
                DATA_DOMAINS:
                    description: A list of data domains to be restricted.
                    type: array
                    items:
                        type: string
       fieldTypes:
           title: FIELD_TYPES
           type: object
           properties:
             FIELD_TYPES:
             description: A list of field types to be restricted.
             type: array
             items:
                type: string
    columns:
      title: COLUMNS
      type: object
      properties:
        COLUMNS:
          description: A list of columns to be restricted.
          type: array
          items:
            type: string
`

Any idea how can we fix this

@iyakobson
Copy link

iyakobson commented Oct 1, 2021

@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"

@gbvanrenswoude
Copy link

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

@nrbw
Copy link

nrbw commented Dec 16, 2021

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

@Jwely
Copy link

Jwely commented Mar 25, 2022

Same bug persists when generating java client with version 5.4

@bremme
Copy link

bremme commented Mar 29, 2022

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?

@sweetmadhu
Copy link

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

@CyberSteve738
Copy link

CyberSteve738 commented Apr 15, 2022

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

@Shryne
Copy link

Shryne commented Apr 27, 2022

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

@macjohnny
Copy link
Member

Everyone is welcome to implement a fix

@Embraser01
Copy link

Embraser01 commented Apr 27, 2022

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

@wing328
Copy link
Member

wing328 commented Apr 27, 2022

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.

@CyberSteve738
Copy link

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

@uri200
Copy link

uri200 commented Jul 19, 2022

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

@wing328
Copy link
Member

wing328 commented Jun 20, 2023

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

I think it should be resolved.

@ysulyma
Copy link

ysulyma commented Jul 27, 2023

@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
Labels
Inline Schema Handling Schema contains a complex schema in items/additionalProperties/allOf/oneOf/anyOf Issue: Bug
Projects
None yet
Development

No branches or pull requests