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
22.05k stars 6.62k forks source link

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

Open charmygarg opened 5 years ago

charmygarg commented 5 years ago
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

macjohnny commented 5 years ago

have you tried the latest version?

Devilsmaul commented 4 years ago

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 commented 4 years ago

I'm also seeing this in 4.2.3.

jamesmfriedman commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

Still seeing this in 5.0.0-beta2 - will https://github.com/OpenAPITools/openapi-generator/pull/7263 fix this?

DenisButCheR commented 4 years ago

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 commented 3 years ago

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 commented 3 years ago

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

Dennis-Nilsson commented 3 years ago

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 commented 3 years ago

@DennisNilssonB3 please try 5.1.0 or the latest stable version

mimkorn commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

@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 commented 3 years ago

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

nrbw commented 2 years ago

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

Jwely commented 2 years ago

Same bug persists when generating java client with version 5.4

bremme commented 2 years ago

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 commented 2 years ago

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

CyberSteve738 commented 2 years ago

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 commented 2 years ago

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

macjohnny commented 2 years ago

Everyone is welcome to implement a fix

Embraser01 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 https://github.com/OpenAPITools/openapi-generator/issues/12920

wing328 commented 1 year ago

@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 commented 1 year ago

@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