Giter VIP home page Giter VIP logo

openapitools / openapi-generator Goto Github PK

View Code? Open in Web Editor NEW
19.8K 215.0 6.1K 842.2 MB

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

Home Page: https://openapi-generator.tech

License: Apache License 2.0

Shell 1.12% Java 92.65% HTML 0.06% Scala 0.05% Apex 0.28% PHP 0.87% Ruby 0.33% Rust 0.09% CSS 0.11% JavaScript 0.37% TypeScript 2.29% Kotlin 1.39% Dockerfile 0.06% Dart 0.01% SCSS 0.01% Blade 0.03% Handlebars 0.12% Groovy 0.07% Haskell 0.12% Emacs Lisp 0.01%
rest-api rest-client sdk generator restful-api api api-client api-server openapi3 openapi

openapi-generator's People

Contributors

4brunu avatar ackintosh avatar arnested avatar borsch avatar casualjim avatar cbornet avatar dependabot[bot] avatar devhl-labs avatar epaul avatar etherealjoy avatar fehguy avatar geekerzp avatar guohuang avatar ityuhui avatar jfcote avatar jfiala avatar jimschubert avatar jmini avatar karismann avatar kuhnroyal avatar richardwhiuk avatar sebastien-rosset avatar shyri avatar spacether avatar sullis avatar tiffmaelite avatar vrolijkx avatar wing328 avatar xhh avatar ybelenko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openapi-generator's Issues

Enum in array of array

The idea of this issue is to extend #66 for other language than java.


There is a high possibility that languages generating inner enums are doing it for “array of enum” but are broken for "array of array of enum” (and more level).

If a mustache template inside {{#vars}}..{{/vars}} is containing something like:

    {{#isEnum}}
    {{^isContainer}}
{{>modelInnerEnum}}
    {{/isContainer}}
    {{/isEnum}}
    {{#items.isEnum}}
      {{#items}}
      {{^isContainer}}
{{>modelInnerEnum}}
      {{/isContainer}}
      {{/items}}
    {{/items.isEnum}}

You should have a look.

I did a search for {{#items.isEnum}}, which give a list of languages:
aspnetcore, csharp, csharp-nancyfx, javascript.

Now CodegenProperty.mostInnerItems is available, you should change the mustache code for:

    {{#isEnum}}
    {{^isContainer}}
{{>modelInnerEnum}}
    {{/isContainer}}
    {{#isContainer}}
    {{#mostInnerItems}}
{{>modelInnerEnum}}
    {{/mostInnerItems}}
    {{/isContainer}}
    {{/isEnum}}

Here a OAS2 that can be used:

swagger: '2.0'
info:
  title: Patrocinium
  description: Patrocinium API
  version: 1.0.0
  termsOfService: 'https://www.patrocinium.com/end-user-licensing-agreement/'
  contact:
    name: Patrocinium
    url: 'https://www.patrocinium.com'
    email: [email protected]
host: papi.patrocinium.com
basePath: /v1
schemes:
  - https
  - http
consumes:
  - application/json
produces:
  - application/json
paths:
  /db/ActionRole/findAndCountAll:
    post:
      tags:
        - db
      description: Find all instances of ActionRole
      operationId: findActionRole
      parameters:
        - in: body
          name: body
          required: false
          schema:
            $ref: '#/definitions/ActionRoleSearch'
      responses:
        '200':
          description: Successful Operation
        '400':
          description: Bad Request
        '403':
          description: Unauthorized
        '500':
          description: Internal Server Error
definitions:
  ActionRoleSearch:
    type: object
    properties:
      attributes:
        description: A list of the attributes that you want to return.
        type: array
        items:
          type: string
          enum:
            - id
            - actionId
            - roleId
            - createdAt
            - updatedAt
            - deletedAt
      order:
        description: A collection of grouped attribute names and directions.
        type: array
        items:
          type: array
          items:
            type: string
            enum:
              - id
              - actionId
              - roleId
              - createdAt
              - updatedAt
              - deletedAt
              - ASC
              - DESC
      limit:
        description: The number of ActionRole instances to return.
        type: integer
        format: int64
        default: 100
        minimum: 1
        maximum: 1000
      offset:
        description: The number of ActionRole instances to offset the returned rows.
        type: integer
        format: int64
        minimum: 0
        default: 0

You can also look at my OAS3 "tree pots" spec: treepots.yaml


If you have any questions, feel free to ask me here.

[DefaultCodegen] Possible missing model for request body for OAS 3.0

Description

Consider the following spec:

openapi: 3.0.0
info:
  title: Test
  version: 1.0.0
servers:
  - url: 'http://test/'
components:
  requestBodies:
    TestBodyInline:
      content:
        application/json:
          schema:
            type: object
            properties:
              test:
                type: string
paths:
  /test/ref/inline:
    post:
      summary: Test
      requestBody:
        $ref: '#/components/requestBodies/TestBodyInline'
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                type: string

For this spec CodegenOperation::bodyParam.dataType equals to "object" and no codegen model is generated for request body. A bit lost why this is happenning because 3 other possible scenarios (inline body + inline schema, inline body + ref schema, ref body + ref schema) work perfectly well.

Discuss static analysis options

Description

I raised the question in #26 about how we could verify standard usage of slf4j loggers at compile time, and whether there is a static analysis tool we could use. We could look into SonarQube, but I've also found a Findbugs plugin at https://github.com/KengoTODA/findbugs-slf4j which would do exactly this.

Should we consider incorporating this type of static analysis now? With so many open source contributors, it would be helpful to standardize on some coding patterns to reduce maintenance overhead.

openapi-generator version

all

OpenAPI declaration file content or url

n/a

Command line used for generation

n/a

Steps to reproduce

n/a

Related issues/PRs
Suggest a fix/enhancement

Incorporate FindBugs or similar into the build.

Add CodegenProperty.nameInSnakeCase

Raised in #22, it would be nice to have CodegenProperty.nameInSnakeCasesimilar to CodegenProperty.nameInCamelCase.

Example:

baseName nameInSnakeCase
petId PET_ID
name NAME
some_value SOME_VALUE

When this feature is implemented, #21 can be changed to be conform to the java naming convention.

[java rest-assured] default is a reserved keyword

Description

When the java generator (with restassured library) creates the project without any tags defined, a DefaultApi class is created.

In ApiClient the method to create this API is:

    public DefaultApi default() {
        return DefaultApi.default(config.baseReqSpec.get());
    }

This does not compile, because "default" is a reserved keyword in java.

The method (in this case only) should be named defaultApi().

openapi-generator version

3.0.0-SNAPSHOT

OpenAPI declaration file content or url
openapi: 3.0.1
info:
  title: ping test
  version: '1.0'
servers:
  - url: 'http://localhost:8000/'
paths:
  /ping:
    get:
      operationId: pingGet
      responses:
        '201':
          description: OK
Work around

Set a tag on the operations in order to change the default value to something else.

Rename "language" to "generator-name" in cli and maven-plugin

On the long term we might want to offer an other way to select the targeted generator.

Probably with multiple switches (to be defined more precisely):

  • language
  • generator type
  • framework
  • ...

Examples:

cli -type=client -language=kotlin
cli -type=server -language=kotlin -framework=ktor

A first move that we could do now with our first release is to rename the term “language” with “generator-name“ in the maven Plugin and in the CLI.

We might support them both options for backward compatibility, but with a warning explaining that “generator-name“ should be preferred.

What are the opinions?

cc: @jimschubert

[DefaultCodegen] NullPointerException with ComposedSchema with oneOf

Description

NullPointerException with composed schema having a oneOf

openapi-generator version

3.0.0-SNAPSHOT

OpenAPI declaration file content or url
openapi: 3.0.1
info:
  title: oneOf test
  version: '1.0'
servers:
  - url: 'http://localhost:8000/'
paths:
  /state:
    get:
      operationId: getState
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ObjA'
                  - $ref: '#/components/schemas/ObjB'
                discriminator:
                  propertyName: realtype
                  mapping:
                    a-type: '#/components/schemas/ObjA'
                    b-type: '#/components/schemas/ObjB'
    post:
      operationId: create
      requestBody:
        content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ObjA'
                  - $ref: '#/components/schemas/ObjB'
                discriminator:
                  propertyName: realtype
                  mapping:
                    a-type: '#/components/schemas/ObjA'
                    b-type: '#/components/schemas/ObjB'
        required: true
      responses:
        '201':
          description: OK
components:
  schemas:
    ObjA:
      type: object
      properties:
        realtype:
          type: string
        message:
          type: string
    ObjB:
      type: object
      properties:
        realtype:
          type: string
        description:
          type: string
        code:
          type: integer
          format: int32

Discuss: end of life scheduling for outdated templating

I'd like to open a discussion about how we notify users of removing functionality.

As a specific example, Microsoft stopped support of .NET 4, 4.5, and 4.5.1 in January 2016. We still maintain 4/4.5 options officially even though 4.5.2 is an in place replacement to the other versions. Removing any amount of conditionals in the C# templates would improve maintainability.

While I understand that users often have reasons for requiring EOL'd versions, removing these from official maintenance doesn't necessarily remove a user's ability to create a custom template (or refer to a template version prior to template support being removed). Since these unmaintained framework versions no longer receive security updates, I feel like maintaining them may require a warning that these are no longer maintained by Microsoft.

What are the thoughts about creating a template archive repository?

[PHP] Deserializing array of objects may not work

Description

When data structure defines array of object, deserializing doesn't work as the nested data may be an array instead of stdclass.

Swagger-codegen version

3.0.0-SNAPSHOT

Swagger declaration file content or url
  /path:
    post:
      parameters:
        - in: body
          required: true
          name: objectName
          schema:
            type: object
            properties:
              arrayInObject:
                type: array
                minItems: 1
                items:
                  $ref: '#/definitions/SomeObject'
Suggest a fix/enhancement

Cast data to stdclass, if data is array, when deserializing data

CLI: Exit status should be 1 when no/wrong arguments are passed

Inspired by #124

When the cli is run with wrong or no arguments, it returns the text:

Available languages (generators): [ada, ada-server, android, apache2, apex, aspnetcore, bash, clojure, cwiki, cpp-qt5, cpp-pistache-server, cpp-restbed-server, cpp-restsdk, cpp-tizen, csharp, csharp-dotnet2, csharp-nancyfx, dart, eiffel, elixir, elm, erlang-client, erlang-server, flash, scala-finch, go, go-server, groovy, kotlin, kotlin-server, haskell-http-client, haskell, java, jaxrs-cxf-client, java-inflector, java-msf4j, java-pkmst, java-play-framework, java-undertow-server, java-vertx, jaxrs-cxf, jaxrs-cxf-cdi, jaxrs-jersey, jaxrs-resteasy, jaxrs-resteasy-eap, jaxrs-spec, javascript, javascript-closure-angular, jmeter, lua, nodejs-server, objc, openapi, openapi-yaml, perl, php, php-lumen, php-slim, php-silex, php-symfony, php-ze-ph, powershell, python, python-flask, r, ruby, ruby-on-rails, ruby-sinatra, rust, rust-server, scalatra, scala-akka, scala-httpclient, scala-gatling, scala-lagom-server, scalaz, spring, dynamic-html, html, html2, swift2-deprecated, swift3, swift4, typescript-angular, typescript-angularjs, typescript-aurelia, typescript-fetch, typescript-inversify, typescript-jquery, typescript-node]

Take this bash script:

#!/bin/sh

java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar
STATUS="${?}"
echo "Status: ${STATUS}"

The error status should be 1 and not 0

Swagger-Parser state

This issue is to discuss the state of one of our upstream dependency Swagger-Parser.

Original project: https://github.com/swagger-api/swagger-parser/pulls

Our fork: https://github.com/OpenAPITools/swagger-parser/pulls
In our fork, we have started to do some fixes on the 2.0-OpenAPITools branch.


Personally I would prefer to have the issues fixed in the original project. Otherwise this means that we will have to publish a release of OpenAPITools/swagger-parser under new maven coordinates (using our groupId)

I would prefer not fragmenting the swagger-parser project.

I am using other tools like openapi-diff and I would like all project to use the same version of swagger-parser. Otherwise this means that we will have a dependency management hell.


I propose that we still open issue and file PRs in the original swagger-parser project. I know there is little reaction at the moment, but it would be better on the long term.

We can also add all the PRs we have created on the original project to our 2.0-OpenAPITools

If they do not integrate our fixes we will be forced to create a release of org.openapitools:swagger-parser based on the 2.0-OpenAPITools. But I hope this will not be necessary.

[Typescript-Node] Incorrect serialization of subclasses in generated code

Description

When using a generated client, serialization only looks at the referenced type when serializing properties of the object. If you are using inheritance, you will lose properties of the subclasses when you serialize.

Openapi-codegen version

3.0.0

Swagger declaration file content or url
swagger: "2.0"
info:
  version: "1.0.0"
  title: Price Lists Service
# during dev, should point to your local machine
host: localhost:10010
# basePath prefixes all resource paths 
basePath: /
# 
schemes:
  # tip: remove http to make production-grade
  - http
# format of bodies a client can send (Content-Type)
consumes:
  - application/json
# format of the responses to the client (Accepts)
produces:
  - application/json
paths:
  /pricelists/{priceListId}/pricepoints/{pricePointId}:
    x-swagger-router-controller: pricePoints
    put:
      description: Updates a price point
      operationId: updatePricePoint
      parameters:
        - name: priceListId
          in: path
          description: Unique id of the price list to retrieve
          required: true
          type: integer
          format: int64
          minimum: 0
        - name: pricePointId
          in: path
          description: Unique id of the price point to update
          required: true
          type: integer
          format: int64
          minimum: 0
        - name: pricePoint
          in: body
          description: Price point to update
          required: true
          schema:
            $ref: "#/definitions/UpdatePricePointRequest"
      responses:
        200:
          description: Success
          schema:
            $ref: "#/definitions/PricePoint"
        400:
          description: Bad Request
          schema:
            $ref: "#/definitions/BadRequestResponse"
        404:
          description: Not Found
          schema:
            $ref: "#/definitions/NotFoundResponse"
        409:
          description: Conflict
          schema:
            $ref: "#/definitions/ConflictResponse"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
      description: Deletes a price point
      operationId: deletePricePoint
      parameters:
      - name: priceListId
        in: path
        description: Unique id of the price list
        required: true
        type: integer
        format: int64
        minimum: 0
      - name: pricePointId
        in: path
        description: Unique id of the price point to delete
        required: true
        type: integer
        format: int64
        minimum: 0
      responses:
        204:
          description: Success
          schema:
            type: string
        400:
          description: Bad Request
          schema:
            $ref: "#/definitions/BadRequestResponse"
        404:
          description: Not Found
          schema:
            $ref: "#/definitions/NotFoundResponse"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
  /swagger:
    x-swagger-pipe: swagger_raw
# complex objects have schema definitions
definitions:
    type: object
    properties:
      restrictions:
        $ref: "#/definitions/PricePointRestrictions"
  PricePointRestrictions:
    type: array
    items:
      $ref: "#/definitions/PricePointRestriction"
  PricePointRestriction:
    type: object
    discriminator: restrictionType
    required:
      - restrictionType
    properties:
      restrictionType:
        type: string
        enum:
        - EntityRestriction
  EntityRestriction:
    type: object
    allOf:
      - $ref: "#/definitions/PricePointRestriction"
      - required:
          - entityId
          - entityType
        properties:
          entityId:
            type: string
          entityType:
            type: string
            format: string
            enum:
            - sku
      type: object
    required:
    - entityId
    - entityType
    - price
    properties:
      entityId:
        type: string
      entityType:
        type: string
        format: string
        enum:
        - product
      price:
        type: number
        format: double
        minimum: 0.00
  PricePoint:
    type: object
    required:
    - id
    - entryId
    - pricePointType
    - restrictions
    - price
    properties:
      id:
        type: integer
        format: int64
        minimum: 0
      entryId:
        type: integer
        format: int64
        minimum: 0
      pricePointType:
        type: string
        format: string
        enum:
        - addition
        - override
      restrictions:
        type: array
        items:
          $ref: "#/definitions/PricePointRestriction"
      price:
        type: number
        format: double
        minimum: 0.00
    type: object
    required:
      - pricePointType
      - restrictions
      - price
    properties:
      pricePointType:
        type: string
        format: string
        enum:
        - addition
        - override
      restrictions:
        type: array
        minItems: 1
        items:
          $ref: "#/definitions/PricePointRestriction"
      price:
        type: number
        format: double
        minimum: 0.00
  UpdatePricePointRequest:
    type: object
    required:
      - pricePointType
      - restrictions
      - price
    properties:
      pricePointType:
        type: string
        format: string
        enum:
        - addition
        - override
      restrictions:
        type: array
        minItems: 1
        items:
          $ref: "#/definitions/PricePointRestriction"
      price:
        type: number
        format: double
        minimum: 0.00
  BadRequestResponse:
    type: object
    required:
    - errorCode
    - messages
    properties:
      errorCode:
        type: string
        example: "400.5.2.0"
      messages:
        type: array
        items:
          type: string
        example:
        - Message here about why the request is invalid
        - Another message here about why the request is invalid
  ConflictResponse:
    type: object
    required:
    - errorCode
    - messages
    properties:
      errorCode:
        type: string
        example: "409.5.2.0"
      messages:
        type: array
        items:
          type: string
        example:
        - Name 'EntryType' is already in use
  ErrorResponse:
    type: object
    required:
    - errorCode
    - messages
    properties:
      errorCode:
        type: string
        example: "500.5.2.0"
      messages:
        type: array
        items:
          type: string
        example:
        - "Something went wrong"
  NotFoundResponse:
    type: object
    required:
    - errorCode
    - messages
    properties:
      errorCode:
        type: string
        example: "404.5.2.0"
      messages:
        type: array
        items:
          type: string
        example:
        - Not Found
  ServiceUnavailableResponse:
    type: object
    required:
      - errorCode
      - messages
    properties:
      errorCode:
        type: string
        example: "503.5.2.0"
      messages:
        type: array
        items:
          type: string
        example:
        - Service is currently unavailable
Command line used for generation

java -jar .\openapi-generator-cli.jar generate -i /path/to/swagger.yaml -l typescript-node -o /path/to/target/directory

Steps to reproduce

With the generated code, run the following:

import { 
    DefaultApi, UpdatePricePointRequest, PricePointRestriction, EntityRestriction 
} from "/path/to/target/directory";

var api:DefaultApi = new DefaultApi();
var updatePricePointRequest: UpdatePricePointRequest = new UpdatePricePointRequest();
updatePricePointRequest.price = 0
updatePricePointRequest.pricePointType = UpdatePricePointRequest.PricePointTypeEnum.Override;
updatePricePointRequest.restrictions = [
    {
       restrictionType: PricePointRestriction.RestrictionTypeEnum.EntityRestriction,
       entityId: 'Success',
       entityType: EntityRestriction.EntityTypeEnum.Sku
    }
];
api.updatePricePoint(0, 0, updatePricePointRequest);

If you step into the updatePricePoint call to where it goes to serialize the list of restrictions, you'll notice that entityId and entityType get left off the serialized object, so that when it is sent onto the server, it is invalid.

Generated java client: maven-javadoc-plugin error

Description

Running maven in a generated java client can not be compiled due to javadoc error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.10.4:jar (attach-javadocs) on project petstore-openapigen-java: MavenReportException: Error while generating Javadoc: 
[ERROR] Exit code: 1 - /____/petstore-openapigen-java/src/main/java/org/openapitools/client/api/PetApi.java:298: error: unknown tag: String
[ERROR]      * @param status Status values that need to be considered for filter (optional, default to new ArrayList<String>())
[ERROR]                                                                                                             ^
[ERROR] /____/petstore-openapigen-java/src/main/java/org/openapitools/client/api/PetApi.java:359: error: unknown tag: String
[ERROR]      * @param status Status values that need to be considered for filter (optional, default to new ArrayList<String>())
[ERROR]                                                                                                             ^
[ERROR] /____/petstore-openapigen-java/src/main/java/org/openapitools/client/api/PetApi.java:371: error: unknown tag: String
[ERROR]      * @param status Status values that need to be considered for filter (optional, default to new ArrayList<String>())
[ERROR]                                                                                                             ^
[ERROR] /____/petstore-openapigen-java/src/main/java/org/openapitools/client/api/PetApi.java:384: error: unknown tag: String
[ERROR]      * @param status Status values that need to be considered for filter (optional, default to new ArrayList<String>())
[ERROR]                                                                                                             ^
[ERROR] 
[ERROR] Command line was: /Library/Java/JavaVirtualMachines/jdk1.8.0_161.jdk/Contents/Home/jre/../bin/javadoc @options @packages
openapi-generator version

3.0.0-SNAPSHOT

OpenAPI declaration file content or url

Normal petstore.json

Command line used for generation

Java code:

JavaClientCodegen config = new org.openapitools.codegen.languages.JavaClientCodegen();
config.setArtifactId("some-artifactId");
config.setJava8Mode(true);
config.setHideGenerationTimestamp(true);
config.setOutputDir(outputDir);

final OpenAPI openAPI = new OpenAPIParser().readLocation(folder + "/" + inputSpecName, null, new ParseOptions()).getOpenAPI()

final ClientOptInput opts = new ClientOptInput();
opts.setConfig(config);
opts.setOpenAPI(openAPI);
opts.setOpts(new ClientOpts());
new DefaultGenerator().opts(opts).generate();
Steps to reproduce

run mvn verify in petstore-openapigen-java/

Suggest a fix/enhancement

In the javadoc section in the template there is a difference between {{type}} and {{{type}}} (one is wrong).

I am not sure why we do not catch it in the CI server. Do we run mvn verify there?

[DefaultGenerator] NullPointerException when no components defined

Description

When there isn't any component defined in the specification, there is a NullPointerException in org.openapitools.codegen.utils.ModelUtils.getUnusedSchemas(OpenAPI)

Exception in thread "main" java.lang.NullPointerException
	at org.openapitools.codegen.utils.ModelUtils.getUnusedSchemas(ModelUtils.java:96)
	at org.openapitools.codegen.DefaultGenerator.generate(DefaultGenerator.java:781)
	at fr.jmini.openapi.openapitools.generator.TestOpenapitoolsCodegenMain.convert(TestOpenapitoolsCodegenMain.java:79)
openapi-generator version

3.0.0-SNAPSHOT

OpenAPI declaration file content or url
openapi: 3.0.1
info:
  title: ping test
  version: '1.0'
servers:
  - url: 'http://localhost:8000/'
paths:
  /ping:
    get:
      operationId: pingGet
      responses:
        '201':
          description: OK

NullPointerException when run "validate" with OAS2 spec

Description
$ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar validate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
Validating spec file (modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml)
Exception in thread "main" java.lang.NullPointerException
        at java.util.HashSet.<init>(HashSet.java:118)
        at org.openapitools.codegen.cmd.Validate.run(Validate.java:44)
        at org.openapitools.codegen.OpenAPIGenerator.main(OpenAPIGenerator.java:52)
openapi-generator version

Latest master

Suggest a fix/enhancement

It may caused by SwaggerConverter as the converter doesn't set message.

In case of parsing OAS3, OpenAPIDeserializer sets message.

I think that SwaggerConverter should set the message as well.

[C#] Use html entities in javadoc of generated code

Description

Similar to #106, we want to apply similar fix to C# client: https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/csharp/api.mustache#L33

openapi-generator version

Latest master

Related issues/PRs

https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/csharp/api.mustache#L33

Suggest a fix/enhancement

This change should be fairly straightforward. If anyone wants to help on this, please reply to let us know.

DefaultGenerator: unusedSchemas contains too many schemas

Some model object are missing when the server is configured to consume both application/json and application/x-www-form-urlencoded.

With this example the model SomeObject is not generated:

swagger: '2.0'
info:
  title: Test
  description: Test API
  version: 1.0.0
host: some.example.com
basePath: /v1
schemes:
  - https
  - http
consumes:
  - application/json
  - application/x-www-form-urlencoded
produces:
  - application/json
paths:
  /testMe:
    post:
      tags:
        - db
      operationId: testMeOp
      parameters:
        - in: body
          name: body
          required: false
          schema:
            $ref: '#/definitions/SomeObject'
      responses:
        '200':
          description: Successful Operation
definitions:
  SomeObject:
    type: object
    properties:
      p1:
        type: string
      p2:
        type: integer
        format: int32

This is due to org.openapitools.codegen.utils.ModelUtils.getUnusedSchemas(OpenAPI) not working as expected.

I am not sure if the dual consumes definition is correct or not (it is derived from a spec send by a used), but we could also imagine an other case with 2 path. In one JSON is expected as request body, in the other an application/x-www-form-urlencoded request body. In this case, the schema is also used.

In my opinion the logic to compute the unused schema should be to compute all the used schema and subtract them from a set containing all schemas.

[java client, gson] Expose @SerializedName value as constant

Sometimes when you are writing tests for an API (with Rest-Assured in my case) you can not use the fluent API to build request, because you want to create an alternative request (malformed, corner case...)

You can use rest-assured RequestSpecBuilder for that. You then write code like this:

        final String updateBody = "{"
                + "\"id\": \"" + req.getId() + "\", "
                + "\"version\": \"" + req.getVersion() + "\", "
                + "\"name\": \"" + req.getName() + "\", "
                + "\"billingAddressId\": null, "
                + "\"contactAddressId\": null, "
                + "\"metadata\": null}";

        final Account account = createSuperAdminApi().accountsUpdate().simulateQuery(true)
                .reqSpec(b -> b.setBody(updateBody))
                .executeAs(r -> r.thenReturn());

I would be great instead of hard-coding the json member like this, to be able to reference constants:

        final String updateBody = "{"
                + "\""+ Acount.SERIALIZED_NAME_Id +"\": \"" + req.getId() + "\", "
                + "\""+ Acount.SERIALIZED_NAME_Version +"\": \"" + req.getVersion() + "\", "
                + "\""+ Acount.SERIALIZED_NAME_Name +"\": \"" + req.getName() + "\", "
                + "\""+ Acount.SERIALIZED_NAME_BillingAddressId +"\": null, "
                + "\""+ Acount.SERIALIZED_NAME_ContactAddressId +"\": null, "
                + "\"metadata\": null}";

This way, when the API evolves, the Java compiler indicates that something needs to be changed in the test case (the same way that the fluent api is also changed).

homebrew doesn't exist

documentation refers to homebrew installation, but I get:

$ brew install openapi-generator
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 3 taps (homebrew/core, caskroom/versions, caskroom/cask).
==> Updated Formulae
azure-cli                                                              dspdfviewer                                                            presto

Error: No available formula with the name "openapi-generator"
==> Searching for a previously deleted formula (in the last month)...
Warning: homebrew/core is shallow clone. To get complete history run:
  git -C "$(brew --repo homebrew/core)" fetch --unshallow

Error: No previously deleted formula found.
==> Searching for similarly named formulae...
==> Searching local taps...
Error: No similarly named formulae found.
==> Searching taps...
==> Searching taps on GitHub...
Error: No formulae found in taps.

[rust-server] non-valid Rust produced in switch to OpenAPI v3

The rust-server generator currently doesn't produce valid Rust. Let's fix this.

Current known problems:

  • Lots of TODOs/commented out code in RustServerCodegen.java
  • Lingering references to 'swagger-codegen'
  • It looks as if we used to do some sort of custom reference parsing. We end up with e.g. SuccessfulOperation ( #/components/schemas/Pet ). It looks as if a fix for a similar issue recently went in d690f42 - maybe we can do the same thing here?
  • pub struct ApiResponse(object);
  • CI

CI aside, this issue can be closed when ./bin/rust-server-petstore.sh produces valid Rust.

(I may take a look at this at some point, but suspect it's unlikely in the immediate future. Others are very welcome to pick this up - I'd be happy to help/support such an effort.)

Clean up Javadoc warning when building the project

Description

File a PR to clean up the Javadoc warnings when for example building openapi-generator-online:

14 warnings
[WARNING] Javadoc Warnings
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:47: warning: no @return
[WARNING] default ResponseEntity<List<String>> clientOptions() {
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:63: warning: no @param for fileId
[WARNING] default ResponseEntity<Resource> downloadFile(String  fileId) {
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:63: warning: no @return
[WARNING] default ResponseEntity<Resource> downloadFile(String  fileId) {
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:71: warning: no @param for language
[WARNING] default ResponseEntity<ResponseCode> generateClient( String  language,
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:71: warning: no @param for generatorInput
[WARNING] default ResponseEntity<ResponseCode> generateClient( String  language,
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:71: warning: no @return
[WARNING] default ResponseEntity<ResponseCode> generateClient( String  language,
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:88: warning: no @param for framework
[WARNING] default ResponseEntity<ResponseCode> generateServerForLanguage( String  framework,
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:88: warning: no @param for generatorInput
[WARNING] default ResponseEntity<ResponseCode> generateServerForLanguage( String  framework,
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:88: warning: no @return
[WARNING] default ResponseEntity<ResponseCode> generateServerForLanguage( String  framework,
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:105: warning: no @param for language
[WARNING] default ResponseEntity<Map<String, CliOption>> getClientOptions(String  language) {
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:105: warning: no @return
[WARNING] default ResponseEntity<Map<String, CliOption>> getClientOptions(String  language) {
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:113: warning: no @param for framework
[WARNING] default ResponseEntity<Map<String, CliOption>> getServerOptions( String  framework) {
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:113: warning: no @return
[WARNING] default ResponseEntity<Map<String, CliOption>> getServerOptions( String  framework) {
[WARNING] ^
[WARNING] /Users/williamcheng/Code/3.0/openapi-generator/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/api/GenApiDelegate.java:121: warning: no @return
[WARNING] default ResponseEntity<List<String>> serverOptions() {
[WARNING] ^

openapi-generator version

Latest master

Steps to reproduce

mvn clean package

Suggest a fix/enhancement

If anyone wants to work on this, please reply to let us know.

Models are now typed as Object when properties of another Model

Description

This was asked in chat, and I've done some evaluation to determine what's going on. Models which are properties of other models are now considered Object rather than the property type.

diff --git a/samples/client/petstore/kotlin/docs/Pet.md b/samples/client/petstore/kotlin/docs/Pet.md
index ec7756007..4b25ccb3e 100644
--- a/samples/client/petstore/kotlin/docs/Pet.md
+++ b/samples/client/petstore/kotlin/docs/Pet.md
@@ -5,7 +5,7 @@
 Name | Type | Description | Notes
 ------------ | ------------- | ------------- | -------------
 **id** | **kotlin.Long** |  |  [optional]
-**category** | [**Category**](Category.md) |  |  [optional]
+**category** | [**kotlin.Any**](kotlin.Any.md) | A category for a pet |  [optional]
 **name** | **kotlin.String** |  | 
 **photoUrls** | **kotlin.Array&lt;kotlin.String&gt;** |  | 
 **tags** | [**kotlin.Array&lt;Tag&gt;**](Tag.md) |  |  [optional]
diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt
index 583dd3fb3..3ca832e7b 100644
--- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt
+++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt
@@ -11,14 +11,13 @@
 */
 package org.openapitools.client.models
 
-import org.openapitools.client.models.Category
 import org.openapitools.client.models.Tag
 
 import com.squareup.moshi.Json
 /**
  * A pet for sale in the pet store
  * @param id 
- * @param category 
+ * @param category A category for a pet
  * @param name 
  * @param photoUrls 
  * @param tags 
@@ -28,7 +27,8 @@ data class Pet (
     val name: kotlin.String,
     val photoUrls: kotlin.Array<kotlin.String>,
     val id: kotlin.Long? = null,
-    val category: Category? = null,
+    /* A category for a pet */
+    val category: kotlin.Any? = null,
     val tags: kotlin.Array<Tag>? = null,
     /* pet status in the store */
     val status: Pet.Status? = null

Apparently, our petstore example for many generated samples only nest models once (Category under Pet#category). This bug appears to happen for any nested models. Nested enums and arrays of types are unaffected.

openapi-generator version

master (752b36e)

OpenAPI declaration file content or url

n/a

Command line used for generation

Any generator under ./bin with nested models

Steps to reproduce
  • pull current master branch (752b36e)
  • execute mvn clean package install
  • execute ./bin/kotlin-client-petstore.sh
  • execute cat samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt

Notice that category is now kotlin.Any? rather than Category as it was previously.

Related issues/PRs
  • Introduced via #45
Suggest a fix/enhancement

Nothing substantial to suggest. Maybe copying non-empty properties to the new schema rather than replacing the reference?


@jmini you commented in the PR that the fix is temporary. However, I consider the issue a significant one.

It looks like this block is the bug:

+            Schema prop = entry.getValue();
+            if (allDefinitions != null && prop != null && StringUtils.isNotEmpty(prop.get$ref())) {
+                String refName = ModelUtils.getSimpleRef(prop.get$ref());
+                prop = allDefinitions.get(refName);
+            }

I haven't stepped through the code to verify, but it seems to me that this would be falling back to Object where it shouldn't be. I saw that you opened a bug with swagger-parser for the json-schema properties that don't get exposed as expected. I think that parser bug is unrelated to this bug.

For reference, I tracked this down via git bisect using:

Would you mind giving this a quick look? I had planned to get into a fix, but I wasted a big of time with my evaluation script (running kotlin-client generator, then checking kotlin-server output produced only HEAD as the bad commit).

Inline Models get typed as `Object`

Description

When I generate code using the attached yaml file I still run into the issue from #79. The difference seems to be my Pet's name object is inline.

openapi-generator version

3.0.0-SNAPSHOT (current master)

OpenAPI declaration file content or url
swagger: '2.0'

info:
  version: '1.0.0'
  title: Test
  description: test

paths:
  /pet:
    get:
      operationId: search
      produces:
        - 'application/json'
      parameters: []
      responses:
        200:
          schema:
            type: array
            items:
              $ref: '#/definitions/Pet'

definitions:
  Pet:
    type: object
    properties:
      name:
        type: object
        properties:
          firstName:
            type: string
          lastName:
            type: string
      favoriteFood:
        type: string
Command line used for generation
$ mvn clean install
$ java -jar target/openapi-generator-cli.jar generate -i openapi.yaml -l typescript-angular -o /tmp/generated
$ cat generated/model/pet.ts 
/**
 * Test
 * test
 *
 * OpenAPI spec version: 1.0.0
 * 
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */


export interface Pet { 
    name?: any;
    favoriteFood?: string;
}
Steps to reproduce
  • Save the file
  • Run the commands

cc: @jimschubert @jmini

Replace '--generator-name' with multiple switches to select a generator

On the long term we might want to offer an other way to select the targeted generator.

Probably with multiple switches (to be defined more precisely):

  • language
  • generator type
  • framework
  • ...

Examples:

cli -type=client -language=kotlin
cli -type=server -language=kotlin -framework=ktor

A first step in this direction was made with #39, where we have renamed -l (--lang) into -g (--generator-name).

With the next version (4.0.0 ?) we might want to continue to work on this by providing an other way to lookup a generator with multiple switches.

This is open for feedback.

cc: @jimschubert

JaxRS Server still use Swagger v2 as dependency

Generated JaxRS Server uses this library as dependency:

    <dependency>
      <groupId>io.swagger</groupId>
      <artifactId>swagger-jersey2-jaxrs</artifactId>
      <version>1.5.15</version>
    </dependency>

It should be:

    <dependency>
      <groupId>io.swagger.core.v3</groupId>
      <artifactId>swagger-jaxrs2</artifactId>
      <version>2.0.1</version>
    </dependency>

Of course the templates need to be changed in order to adopt the new notation and annotations...


The most visible impact is on the capability for the server to self describe itself.

When you run mvn clean package jetty:run inside the samples/server/petstore/jaxrs/jersey2/ folder and then call http://localhost:8080/v2/swagger.yaml, you obtain the corresponding spec:

swagger: "2.0"
info:
  ...
host: "petstore.swagger.io:80"
basePath: "/v2"
tags:
...
schemes:
- "http"
paths:
  /another-fake/dummy:
    patch:
      ...
  /fake/outer/boolean:
    post:
      tags:
      - "fake"
      summary: ""
      description: "Test serialization of outer boolean types"
      operationId: "fakeOuterBooleanSerialize"
      consumes:
      - "*/*"
      produces:
      - "*/*"
      parameters:
      - in: "body"
        name: "body"
        description: "Input boolean as post body"
        required: false
        schema:
          type: "boolean"
      responses:
        200:
          description: "Output boolean"
          schema:
            type: "boolean"
  /fake/outer/composite:
    post:
      ...
  /fake/outer/number:
    ...

The big next step for the JaxRS generators will be to generate code that will be using Swagger v3 artefacts. Then the page to call to get the spec will be http://localhost:8080/v2/openapi.yaml

Code clean-up: refactor CodegenResponse, CodegenProperty and CodegenParameter

CodegenResponse, CodegenProperty and CodegenParameter are very similar, but for the moment they to not share nothing.

With OAS2 specification, it made sense to have three objects because every of these concepts was different in the spec. Now with OAS3, everything is Schema based. But in our methods fromModel(..), fromProperty(..) and fromResponse(..) reimplement everything three times…

The first step will be to identify what is common between CodegenResponse, CodegenProperty and CodegenParameter. A new abstract Codegen should be created: AbstractSchemaBasedCodegen (or something like that). It contains the common stuff and it is derived from the schema.

Then we will be able to remove the redundancy in DefaultCodegen and we will have something that works the same way for consumers of CodegenResponse, CodegenProperty and CodegenParameter.

[Kotlin] Invalid enum var names

Description

When enums name start with a number, the generated code won't compile

openapi-generator version

3.0.0-SNAPSHOT

OpenAPI declaration file content or url
"enum":[
    "1name"
]
Command line used for generation

java -jar openapi-generator-cli.jar generate -i swagger.json -c config.json -l kotlin -o tmp

Steps to reproduce

Add an enum parameter to swagger file; generate and compile.

Related issues/PRs
Suggest a fix/enhancement

The enumeration name can be prefixed by an underscore, it's done like this for the model name.

Another solution is to surround illegals names with backticks, but enum may be tricky to use (Status.1available). And what I understand of kotlin coding convention is backticks are acceptable only for names in tests.

Vert.x Web Client & Server code generator

Description

Code generator both for client and server with Eclipse Vert.x

Client codegen will be Vert.x generic, supporting Java, Java with RxJava 2 & Kotlin for now. It will have a @Vertx interface as entrypoint

Server codegen will be for Java (for now)

I'm working on it

Users should be able to query configurable vendor extensions via CLI

Description

Refer to https://github.com/OpenAPITools/openapi-generator/wiki/Vendor-Extensions

Generators which support user-configurable vendor extensions should expose these as valuable information to the user via CLI.

openapi-generator version

n/a

Related issues/PRs

n/a

Suggest a fix/enhancement

To reduce the amount of information exposed via config-help, and because vendor extensions aren't generally a means for configuring codegen but for extending output, we may want to consider making these queryable as a subcommand.

Some possible options for CLI usage:

$ cli config-help extensions --generator-name=java-feign
Generator: java-feign
Extensions:
  x-accepts
      A single Accepts value as the Feign API client needs a single value for Accepts header

  x-content-type
      A single "Content-Type" value as the Feign API client needs a single value for Content-Type header
$ cli config-help extensions --generator-name=cwiki
Generator: cwiki
Extensions: none

We may even want to consider exposing a metadata-only command, and moving config-help as a sub-command, but we can worry about shuffling the CLI options around within a minor release. For this feature request, I'd like to get extension information queryable.

Issue with Javascript Petstore test

Description

Got the following errors with JS tests:

  161 passing (1s)
  1 failing

  1) PetApi should create and get pet:
     Uncaught Error: expected undefined to be an instance of exports
      at Assertion.assert (node_modules/expect.js/index.js:96:13)
      at Assertion.a.Assertion.an (node_modules/expect.js/index.js:279:12)
      at Function.a (node_modules/expect.js/index.js:499:17)
      at test/api/PetApi.spec.js:72:20
      at src/ApiClient.js:493:9
      at Request.callback (node_modules/superagent/lib/node/index.js:668:14)
      at node_modules/superagent/lib/node/index.js:883:18
      at IncomingMessage.<anonymous> (node_modules/superagent/lib/node/parsers/json.js:16:7)
      at endReadableNT (_stream_readable.js:1056:12)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)

https://github.com/OpenAPITools/openapi-generator/blob/master/samples/client/petstore/javascript/test/api/PetApi.spec.js#L72

Migrate relevant wiki content into docs folder of the main repo

See discussion in #57, I try to summarize it here (feel free to discuss, challenge, improve...)


The pages in the wiki:

Intend to be community driven as anyone can update it easily without a PR. (we did see contributions from the community to add more pages like FAQ over time)

The items in the docs/ folder in the repo:

Is something that should be updated with approval/review as is represents the project viewpoints.


To avoid confusion, we might add a note on top of wiki pages, to indicate that there is more in the official docs. We also want to consolidate content by moving great wiki page contribution related to our project into our docs/ folder. I is more useful and easily discoverable by our users.

One example, there are at the moment 2 FAQ pages:

  • The FAQ (wiki) is the community driven FAQ as anyone can update it easily without a PR. (we did see contributions from the community to add more FAQs over time)
  • The Q&A in docs (mainly for the launch of openapi-generator) can not be updated without a PR.

Reason for using the main repo:

Multiple reasons for that:

  • Documentation belongs to software change, have a look at this PR, it is great to be able to discuss what needs to be documented.
  • GitHub Wiki does not support PR workflow, which is a great way to do suggestions, reviews and improvements
  • Wiki are not forked in GitHub forks, you need to migrate them separately (they are git repositories, but not well integrated in GitHub UI).
  • Pages inside a repo can be edited like a wiki, it supports all of github's templating (asciidoc, csv rendering, etc) and provide a better editor. Commits can be directly pushed (for owners) or a PR can be opened in a very easy way.
  • Software documentation follows the software branches. Imagine we works on 4.0 and do some bugfix release for 3.0 on a separated 3.x-maintenance branch. With a GitHub wiki you just have a master branch, you can not support both versions in parallel.
  • On the long term the plan is to generate the documentation inside a static website. For that we might need some artifacts that comes from the code itself (like for example the help in the command line that you have updated by hand). In the docs page there should be a placeholder that some content will be injected, and the static-website build tool should put the correct values in the built html manual. When we have this it make even more sense to single source everything in one repo and not in two (the main repo and the wiki repo)

[go] map type object *interface{} convert problem

Description

Definition property "type": "object" gets converted to *interface{} which returns an error when set to a struct or pointer pointer.

openapi-generator version

3.0.0

OpenAPI declaration file content or url
Command line used for generation
Steps to reproduce
Related issues/PRs
Suggest a fix/enhancement

Instead of an *interface{} map the object to map[string]interface{}

[java] no inner enums generated on arrays of enums

Description

When an model is an array of enums, the type is not the correct one.

openapi-generator version

3.0.0-SNAPSHOT

OpenAPI declaration file content or url
openapi: 3.0.1
info:
  title: OpenAPI test
  description: Example spec
  version: 1.0.0
servers:
  - url: 'http://api.company.xyz/call'
paths:
  /some/ping:
    get:
      operationId: op1
      responses:
        '200':
          description: Ok
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArrayOfEnum'
components:
  schemas:
    ArrayOfEnum:
      type: array
      items:
        type: string
        enum:
          - val1
          - val2
          - val3
          - val4
Command line used for generation

java client generator, without any particular option

JavaClientCodegen config = new org.openapitools.codegen.languages.JavaClientCodegen();
config.setArtifactId(artifactId);
config.setJava8Mode(true);

Path outputDirPath = Paths.get(outputDir);

config.setHideGenerationTimestamp(true);
config.setOutputDir(outputDir);

final OpenAPIParser openApiParser = new OpenAPIParser();
final ParseOptions options = new ParseOptions();
final OpenAPI openAPI = openApiParser.readLocation(inputSpec, null, options).getOpenAPI();

final ClientOptInput opts = new ClientOptInput();
opts.setConfig(config);
opts.setOpenAPI(openAPI);
opts.setOpts(new ClientOpts());
new DefaultGenerator().opts(opts).generate();
Suggest a fix/enhancement

Model class is:

public class ArrayOfEnum extends ArrayList<String> {
//...
}

Should be a ArrayList of the enum type (maybe an inner enum) instead of String

Work around:

Use an indirection over $ref:

openapi: 3.0.1
info:
  title: OpenAPI test
  description: Example spec
  version: 1.0.0
servers:
  - url: 'http://api.company.xyz/call'
paths:
  /some/ping:
    get:
      operationId: op1
      responses:
        '200':
          description: Ok
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArrayOfEnum'
components:
  schemas:
    ArrayOfEnum:
      type: array
      items:
        $ref: '#/components/schemas/SomeEnum'
    SomeEnum:
      type: string
      enum:
        - val1
        - val2
        - val3
        - val4

[Node.js] server doesn't work

Description

The errors on when run npm start in nodejs server sample folder:

Error: Unsupported Swagger version: undefined

$ bin/openapi3/nodejs-petstore-server.sh
$ cd samples/server/petstore/nodejs
$ npm start

> [email protected] start /Users/akihito1/src/github.com/ackintosh/openapi-generator/samples/server/petstore/nodejs
> node index.js

/Users/akihito1/src/github.com/ackintosh/openapi-generator/samples/server/petstore/nodejs/node_modules/swagger-tools/lib/helpers.js:169
        throw new Error('Unsupported Swagger version: ' + version);
        ^

Error: Unsupported Swagger version: undefined
    at Object.module.exports.getSpec (/Users/akihito1/src/github.com/ackintosh/openapi-generator/samples/server/petstore/nodejs/node_modules/swagger-tools/lib/helpers.js:169:15)
    at Object.initializeMiddleware (/Users/akihito1/src/github.com/ackintosh/openapi-generator/samples/server/petstore/nodejs/node_modules/swagger-tools/index.js:44:18)
    at Object.<anonymous> (/Users/akihito1/src/github.com/ackintosh/openapi-generator/samples/server/petstore/nodejs/index.js:24:14)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)

npm ERR! Darwin 17.4.0
npm ERR! argv "/Users/akihito1/.nodebrew/node/v6.11.1/bin/node" "/Users/akihito1/.nodebrew/current/bin/npm" "start"
npm ERR! node v6.11.1
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script 'node index.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the swagger-petstore package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node index.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs swagger-petstore
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls swagger-petstore
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/akihito1/src/github.com/ackintosh/openapi-generator/samples/server/petstore/nodejs/npm-debug.log
openapi-generator version

current master

Suggest a fix/enhancement

The error is due to the swagger-tools does not support OAS3.
(It is also occurs with OAS2 as api/openapi.yaml is always output as OAS 3.)

Users using swagger-tools did ask for it:

apigee-127/swagger-tools#529
apigee-127/swagger-express#20

But no reply from Apigee.

In the medium/long term, we'll need to provide another NodeJS server generator based on other (active) frameworks: https://nordicapis.com/13-node-js-frameworks-to-build-web-apis/

[JaxRS] Add "validation-api" dependency in jetty

Description

In a generated project (Java Server with JaxRS), you should be able to run a jetty with

mvn clean package jetty:run

Stacktrace:

WARNING: HK2 service reification failed for [org.glassfish.jersey.server.model.ResourceMethodInvoker$Builder] with an exception:
MultiException stack 1 of 1
java.lang.NoClassDefFoundError: javax/validation/Validator
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
	at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
	at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
	at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
	at org.eclipse.jetty.webapp.WebAppClassLoader.findClass(WebAppClassLoader.java:510)
	at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:441)
	at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:403)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:348)
	at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
	at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
	at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
	at sun.reflect.generics.visitor.Reifier.reifyTypeArguments(Reifier.java:68)
	at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:138)
	at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
	at sun.reflect.generics.repository.FieldRepository.getGenericType(FieldRepository.java:85)
	at java.lang.reflect.Field.getGenericType(Field.java:247)
	at org.glassfish.hk2.utilities.reflection.ReflectionHelper.resolveField(ReflectionHelper.java:153)
	at org.jvnet.hk2.internal.Utilities.getFieldInjectees(Utilities.java:1861)
	at org.jvnet.hk2.internal.ClazzCreator.initialize(ClazzCreator.java:160)
	at org.jvnet.hk2.internal.ClazzCreator.initialize(ClazzCreator.java:179)
	at org.jvnet.hk2.internal.SystemDescriptor.internalReify(SystemDescriptor.java:723)
	at org.jvnet.hk2.internal.SystemDescriptor.reify(SystemDescriptor.java:678)
	at org.jvnet.hk2.internal.ServiceLocatorImpl.reifyDescriptor(ServiceLocatorImpl.java:458)
	at org.jvnet.hk2.internal.ServiceLocatorImpl.narrow(ServiceLocatorImpl.java:2205)
	at org.jvnet.hk2.internal.ServiceLocatorImpl.igdCacheCompute(ServiceLocatorImpl.java:1150)
	at org.jvnet.hk2.internal.ServiceLocatorImpl.access$400(ServiceLocatorImpl.java:122)
	at org.jvnet.hk2.internal.ServiceLocatorImpl$8.compute(ServiceLocatorImpl.java:1144)
	at org.jvnet.hk2.internal.ServiceLocatorImpl$8.compute(ServiceLocatorImpl.java:1141)
	at org.glassfish.hk2.utilities.cache.internal.WeakCARCacheImpl.compute(WeakCARCacheImpl.java:116)
	at org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetDescriptor(ServiceLocatorImpl.java:1215)
	at org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:762)
	at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:704)
	at org.glassfish.jersey.server.internal.routing.Routing$Builder.buildStage(Routing.java:194)
	at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:587)
	at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:184)
	at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:350)
	at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:347)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
	at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:347)
	at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
	at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
	at javax.servlet.GenericServlet.init(GenericServlet.java:244)
	at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:612)
	at org.eclipse.jetty.servlet.ServletHolder.initialize(ServletHolder.java:395)
	at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:871)
	at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:298)
	at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1349)
	at org.eclipse.jetty.maven.plugin.JettyWebAppContext.startWebapp(JettyWebAppContext.java:296)
	at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1342)
	at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741)
	at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:505)
	at org.eclipse.jetty.maven.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:365)
	at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
	at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
	at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
	at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
	at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:163)
	at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
	at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
	at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
	at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
	at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
	at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
	at org.eclipse.jetty.server.Server.start(Server.java:387)
	at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
	at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
	at org.eclipse.jetty.server.Server.doStart(Server.java:354)
	at org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:73)
	at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
	at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:534)
	at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:357)
	at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
	at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
	at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
	at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
	at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
	at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
	at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
	at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
	at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
	at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
	at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
	at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
	at org.apache.maven.cli.MavenCli.execute(MavenCli.java:955)
	at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:290)
	at org.apache.maven.cli.MavenCli.main(MavenCli.java:194)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
	at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
	at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
	at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.ClassNotFoundException: javax.validation.Validator
	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
	at org.eclipse.jetty.webapp.WebAppClassLoader.findClass(WebAppClassLoader.java:510)
	at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:441)
	at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:403)
	... 103 more

I had already fixed it in Swagger v3, see swagger-api/swagger-codegen-generators@11b6cfa. This needs to be ported to this project.

CI Error with ElixirPetstoreClientTests on shippable

https://app.shippable.com/github/OpenAPITools/openapi-generator/runs/94/1/console

[INFO] ------------------------------------------------------------------------
[INFO] Building Elixir Petstore Client 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:2.8:copy-dependencies (default) @ ElixirPetstoreClientTests ---
[INFO] 
[INFO] --- exec-maven-plugin:1.2.1:exec (dep-install) @ ElixirPetstoreClientTests ---
* creating /root/.mix/archives/hex.ez
[INFO] 
[INFO] --- exec-maven-plugin:1.2.1:exec (compile) @ ElixirPetstoreClientTests ---
Resolving Hex dependencies...
Dependency resolution completed:
New:
  mime 1.2.0
  poison 3.1.0
  tesla 0.10.0
All dependencies up to date
** (Mix) You're trying to run :openapi_petstore on Elixir v1.1.0-dev but it has declared in its mix.exs file it supports only Elixir ~> 1.4

I have tried locally:

mvn verify -f samples/client/petstore/elixir/pom.xml

But this requires the mix program.

[java] Enum in array of array

Description

Inner enum classes corresponding to an array of array Schema with Enum are not generated in java.
This was filed as swagger-api/swagger-codegen#7918. I have fixed it in Swagger-Codegen v3 using an handlebars helper. Because we can not do this with JMustache, I think that the Codegen should provide access to something like "inner most items"

openapi-generator version

3.0.0-SNAPSHOT

OpenAPI declaration file content or url

https://gist.github.com/msjoshi/08f95f35610656ec7d45bacb48f7bd22

[Discussion] GitHub labels definition in this project

I think we should define how we will use labels in the project.
See the current list here: https://github.com/OpenAPITools/openapi-generator/issues/labels


What is the difference between bug and invalid ?

Is invalid for an issue that is not correct?


I also think we need to do the difference between something broken in the generator (for example a NullPointer when we run the code) and something that is wrong in the generated code (that is often only for a specific OpenAPI sepecification, and for one target language)


I also think we need a discussion type of issue.

New Generator: Crystal client generator

If anyone is interested in contributing a Crystal client generator, please reply to let us know. We can use reverse engineering to create the Crystal generator and template based on a functional Crystal Petstore client similar to what we did before for PowerShell, Lua, etc.

Please reply to let us know if you want to work on this. Thanks.

Travis CI issue

Description

Travis CI timed out due to the following:

openapi-petstore-0.1.0.0: Test suite tests passed
Completed 14 action(s).
Compiling src/Byte.elm
Some new packages are needed. Here is the upgrade plan.

  Install:
    NoRedInk/elm-decode-pipeline 3.0.0
    elm-lang/core 5.1.1
    elm-lang/html 2.0.0
    elm-lang/http 1.0.0
    elm-lang/virtual-dom 2.0.4
    justinmimbs/elm-date-extra 2.1.1
openapi-generator version

Current master

Related issues/PRs

https://travis-ci.org/OpenAPITools/openapi-generator/builds/380911655

Suggest a fix/enhancement

We may want do disable the elm client test for the time being to see if the issue goes away

DefaultCodegen: code-cleanup, propagate the openAPI instance

In DefaultCodegen we have some methods that work with the current openAPI instance, other that do not.

We have methods that use Map<String,Schema> (corresponding to openAPI.getComponents().getSchemas()) => this corresponds to allDefinitions in a OAS2.

Now that Components in OAS3 is more than just the schemas, all methods should work with openAPI.


In particular:

The method public CodegenModel fromModel(String name, Schema schema) is really confusing. It is used a lot in the tests, but in reality public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allDefinitions) is used.

We should remove public CodegenModel fromModel(String name, Schema schema) or if we keep it, give a more explicit name.

And all Unit-Tests should use: public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> allDefinitions) (or the adapted public CodegenModel fromModel(String name, Schema schema, OpenAPI openAPI) after the change described here)


We will need to refer to Components more and more. For example if we want to solve #8 we need to look at the referenced responses and requestBodies.

Add a check enforce "samples/" folder to be up-to-date

I think that with each PR, the samples/ needs to be completely updated. For the moment people focus only on their generators (which is fine), but this is wrong.

First reason: some CI Jobs are updating /samples with /bin/run-all-petstore and then run each generated project. So they are not executed against code that is checked in, but against code that is generated.

Second reason: for later analysis (understand what was broken when) it is good to have the changes in the same PR.

Third reason: even if you think that you have only updated one generator (say java) your change might have an undesired impact in a other generator. Having it explicitly is good. This is even worth when you change something in DefaultGenerator (see my mistake in #79)


Pre-requisit:

  • All generators needs to support the hide generation timestamp feature.
  • All examples in the samples/ project needs to have been generated once

The check should looks like this and could be added at the end of bin/run-all-petstore:

if ! `git diff-index --quiet HEAD -- `; then
    echo "There are uncommitted changes in working tree after execution of 'bin/run-all-petstore'"
    git status
    echo "Please commit changes"
    exit 1
else
    echo "Git working tree is clean"
fi

Update samples scripts to move args ($@) to end of script text

Description

$@ in our sample scripts should exist at the end of ags. Moving these to the end of ags allows maintainers to evaluate different generator options more easily.

Example (of a script supporting this):

./bin/kotlin-client-petstore.sh --additional-properties dateLibrary=string

This allows maintainers to easily see changes for different options:

$ git diff
diff --git a/samples/client/petstore/kotlin/docs/Order.md b/samples/client/petstore/kotlin/docs/Order.md
index ef31dbf2f..4683c14c1 100644
--- a/samples/client/petstore/kotlin/docs/Order.md
+++ b/samples/client/petstore/kotlin/docs/Order.md
@@ -7,7 +7,7 @@ Name | Type | Description | Notes
 **id** | **kotlin.Long** |  |  [optional]
 **petId** | **kotlin.Long** |  |  [optional]
 **quantity** | **kotlin.Int** |  |  [optional]
-**shipDate** | [**java.time.LocalDateTime**](java.time.LocalDateTime.md) |  |  [optional]
+**shipDate** | **kotlin.String** |  |  [optional]
 **status** | [**inline**](#StatusEnum) | Order Status |  [optional]
 **complete** | **kotlin.Boolean** |  |  [optional]

diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt
index 44a8b1f89..5e5696bbc 100644
--- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt
+++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt
@@ -26,7 +26,7 @@ data class Order (
     val id: kotlin.Long? = null,
     val petId: kotlin.Long? = null,
     val quantity: kotlin.Int? = null,
-    val shipDate: java.time.LocalDateTime? = null,
+    val shipDate: kotlin.String? = null,
     /* Order Status */
     val status: Order.Status? = null,
     val complete: kotlin.Boolean? = null

In bash, $@ is an array holding arguments to the calling script-- essentially argv.

Most of our samples scripts pass the args before the CLI's generate command:

ags="$@ generate -l aspnetcore \
    -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml \ 
    -o samples/server/petstore/aspnetcore \
    --additional-properties packageGuid={3C799344-F285-4669-8FD5-7ED9B795D5C5}"

This doesn't make a lot of sense because the only option we're allowed to pass HERE:

java -jar openapi-generator-cli.jar HERE generate …

Is help. All other options will fail.

Any other special properties allowed by the generator are system properties. Bash already allows this:

JAVA_OPTS=-DdebugOpenAPI=true ./bin/aspnetcore-petstore-server.sh 
# or 
env JAVA_OPTS=-DdebugOpenAPI=true ./bin/aspnetcore-petstore-server.sh 
openapi-generator version

n/a

OpenAPI declaration file content or url

n/a

Command line used for generation

n/a

Steps to reproduce

n/a

Related issues/PRs

n/a

Suggest a fix/enhancement

see description

[java] enum for int array initialized with strings

Description

The generated code for the enums of int types, in an array of said enums is initialized with a string.
Compilation fails

  public enum TypeEnum {
    _0("0"),
    
    _1("1"),
    
    _2("2"),
    
    _3("3")
openapi-generator version

master

OpenAPI declaration file content or url
  TypeIds:
    type: object
    properties:
      type:
        type: array
        items:
          type: integer
          format: int32
          enum:
          - 0
          - 1
          - 2
          - 3
Command line used for generation

java -jar ./openapi-generator-cli.jar generate -i ./Api.yaml -o ./genjava -l java

Steps to reproduce
Related issues/PRs
Suggest a fix/enhancement

[PHP] Handle non-required property as nullable

Description

When a property isn't required, it is not shown in Doc Block, that the getter can actually return "null".
Also it is not shown in the setter, that "null" is a valid value

Swagger-codegen version

3.0.0-SNAPSHOT

Swagger declaration file content or url
  /path
    post:
      parameters:
        - in: body
          required: true
          name: objectName
          schema:
            type: object
            required:
              - requiredPropertyName
            properties:
              requiredPropertyName:
                type: string
              notRequiredPropertyName:
                type: string
Suggest a fix/enhancement

Change returnType in Doc Block for getters to correctly show, that the returned value can be null (if the property is not required).
Also shown in Doc Block for setters, that value can be null (if property is not required)

[PHP] Incorrect return types if multiple responses are defined

Description

If you define multiple responses, the codegen will only support the first one (typically 200).

openapi-generator version

3.0.0-SNAPSHOT

OpenAPI declaration file content or url
  /path
    post:
      responses:
        200:
          schema:
            $ref: '#/definitions/EmptyResponse'
        202:
          schema:
            $ref: '#/definitions/InBackgroundResponse'
Suggest a fix/enhancement

Correctly generate the return-object based on the HTTP Status Code in the Response.
Also fix ReturnType info in DocBlock

[Java rest-assured] check for “redirect” answer

I have a case, where I need to check if a service is sending a 302 code.
I have generated my client with the java generator, using the rest-assured library.

I was expecting to be able to write something like this:

api.myService().param1Query(“value”).execute(r -> r.thenReturn())
				.then()
				.log().ifValidationFails()
				.assertThat()
				.statusCode(HttpStatus.SC_MOVED_TEMPORARILY)
				.header("Location", "https://example.com/");

This does not work, because by default rest-assured follow the redirect.
I get 200 and the content of https://example.com/.
With Rest-Assured, the solution (1) is to add .redirects().follow(false) after RestAssured.given().

But with the client generated by OpenAPI Generator, it is not possible to access the RequestSpecification created by RestAssured.given() (or I did not find how).

In StoreApiTest.java you will use the generated StoreApi.java (the execute(..) method). This execute(..) creates the RestAssured.given(). But in my test I do not have access to it.

Should the generator be extended to generate two execute methods in order to expose requestSpecification for special cases like mine. Something like this:

public <T> T execute(Function<Response, T> handler) {
    return execute(RestAssured.given(), handler);
}

public <T> T execute(RequestSpecification requestSpecification, Function<Response, T> handler) {
    return handler.apply(requestSpecification.spec(reqSpec.build()).expect().spec(respSpec.build()).when().request(DELETE, REQ_URI));
}

(and the same for executeAs...)

Is there a better solution?

(1) https://groups.google.com/forum/#!msg/rest-assured/Sq_83Hc98Oo/2HUszbc6AgAJ

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.