Git Product home page Git Product logo

openapi-generator-cli's Introduction

@openapitools/openapi-generator-cli

Join the Slack chat room

Build Renovate enabled semantic-release

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (both 2.0 and 3.0 are supported). Please see OpenAPITools/openapi-generator.

The OpenAPI Generator is a Java project. openapi-generator-cli will download the appropriate JAR file and invoke the java executable to run the OpenAPI Generator. You must have the java binary executable available on your PATH for this to work.

If you find this tool useful, please consider sponsoring this project financially via https://opencollective.com/openapi_generator or directly to Kay Schecker (the author of this tool) ๐Ÿ™


Version 2.x.x

[update] The command has been renamed

You need to execute openapi-generator-cli instead of openapi-generator from now on.

[added] semver support! ๐ŸŽ‰

To make that happen, a version management was added to the package. The first time you run the command openapi-generator-cli the last stable version of OpenAPITools/openapi-generator is downloaded by default.

That version is saved in the file openapitools.json. Therefore you should include this file in your version control, to ensure that the correct version is being used next time you call the command.

If you would like to use a different version of the OpenAPITools/openapi-generator, you could change it by using one of the following commands:

  • openapi-generator-cli version-manager list
  • openapi-generator-cli version-manager set <versionTags...>

[added] generator config

You will now be able to configure the code generation in openapitools.json. This makes it more convenient to generate code for every file that matches the given glob expression. For more information, please check out the configuration documentation below.

Installation

Locally (recommended)

npm install @openapitools/openapi-generator-cli

or using yarn

yarn add @openapitools/openapi-generator-cli

After the installation has finished you can run npx openapi-generator-cli or add a script like this:

{
  "name": "my-cool-package",
  "version": "0.0.0",
  "scripts": {
    "my-awesome-script-name": "openapi-generator-cli generate -i docs/openapi.yaml -g typescript-angular -o generated-sources/openapi --additional-properties=ngVersion=6.1.7,npmName=restClient,supportsES6=true,npmVersion=6.9.0,withInterfaces=true",
  }
}

Note the whitespace sensitivity when using multiple additional-properties:

--additional-properties=ngVersion=6.1.7,npmName=restClient,supportsES6=true,npmVersion=6.9.0,withInterfaces=true

Globally

npm install -g @openapitools/openapi-generator-cli

or using yarn

yarn global add @openapitools/openapi-generator-cli

After the installation has finished you can run openapi-generator-cli

Usage

Mac/Linux:

openapi-generator-cli generate -g ruby -i https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -o /var/tmp/ruby-client

Windows:

openapi-generator-cli generate -g ruby -i https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -o C:\temp\ruby-client

Configuration

If you have installed the package locally and executed the command openapi-generator-cli at least once, you will find a new file called openapitools.json along with the package.json. Please add this file to your VCS.

Initially the file has the following content:

{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "4.3.1" // or the current latest version ;)
  }
}

This configuration indicates the following:

  • the json file shall be formatted using 2 spaces
  • the jar files shall be downloaded to ./my/custom/storage/dir
  • the generator-cli version 4.3.1 is used

Further it is also possible to configure generators, for example:

{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "4.3.1",
    "storageDir": "~/my/custom/storage/dir", // optional
    "generators": { // optional
      "v2.0": { // any name you like (just printed to the console log or reference it using --generator-key) 
        "generatorName": "typescript-angular",
        "output": "#{cwd}/output/v2.0/#{ext}/#{name}",
        "glob": "examples/v2.0/{json,yaml}/*.{json,yaml}",
        "additionalProperties": {
          "ngVersion": "6.1.7",
          "npmName": "restClient",
          "supportsES6": "true",
          "npmVersion": "6.9.0",
          "withInterfaces": true
        }
      },
      "v3.0": { // any name you like (just printed to the console log or reference it using --generator-key) 
        "generatorName": "typescript-fetch",
        "output": "#{cwd}/output/v3.0/#{ext}/#{name}",
        "glob": "examples/v3.0/petstore.{json,yaml}"
      }
    }
  }
}

If openapi-generator-cli generate is called without further arguments, then the configuration is automatically used to generate your code. ๐ŸŽ‰

Available placeholders
placeholder description example
name just file name auth
Name just file name, but starting with a capital letter Auth
cwd the current cwd /Users/some-user/projects/some-project
base file name and extension auth.yaml
path full path and filename /Users/some-user/projects/some-project/docs/auth.yaml
dir path without the filename /Users/some-user/projects/some-project/docs
relDir directory name of file relative to the glob provided docs
relPath file name and extension of file relative to the glob provided docs/auth.yaml
ext just file extension yaml

Using custom / private maven registry

If you're using a private maven registry you can configure the downloadUrl and queryUrl like this:

{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "5.3.0",
    "repository": {
      "queryUrl": "https://private.maven.intern/solrsearch/select?q=g:${group.id}+AND+a:${artifact.id}&core=gav&start=0&rows=200",
      "downloadUrl": "https://private.maven.intern/maven2/${groupId}/${artifactId}/${versionName}/${artifactId}-${versionName}.jar"
    }
  }
}

If the version property param is set it is not necessary to configure the queryUrl.

Run specific generators

cmd v3.0 runs v2.0 runs
openapi-generator-cli generate --generator-key v3.0 yes no
openapi-generator-cli generate --generator-key v3.0 v2.0 yes yes
openapi-generator-cli generate --generator-key foo no no

Use Docker instead of running java locally

{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "useDocker": true
  }
}

If useDocker option is used, the spec file gets mounted to path /local/<your-spec-file-location> within container. So, if you would configure spec file as -i openapi/my-api.yml if running locally, with useDocker option set, you would have to configure it like this: -i /local/openapi/my-api.yml.

Custom Generators

Custom generators can be used by passing the --custom-generator=/my/custom-generator.jar argument.

Further Documentation

Please refer to the official openapi-generator docs for more information about the possible arguments and a detailed usage manual of the command line interface.

Install previous version

npm install @openapitools/openapi-generator-cli@previous
npm i @openapitools/[email protected]                                         

or using yarn

yarn add @openapitools/openapi-generator-cli@previous
yarn add @openapitools/[email protected]

You like the package?

Please leave a star.

openapi-generator-cli's People

Contributors

ackintosh avatar ardc-shorn avatar bahrmichael avatar birdofpreyru avatar chimurai avatar daniel-shuy avatar dependabot[bot] avatar elmarbeckmann avatar ermik avatar gervasiocaj avatar gregorwolf avatar hiddewie avatar jontze avatar kageurufu avatar kay-schecker avatar keks42 avatar konstantinlukaschenko avatar ltomes avatar lucianbuzzo avatar mcaden avatar millotp avatar mok-liee avatar nicholasphair avatar nilskuhn avatar renovate-bot avatar renovate[bot] avatar romansattler avatar wing328 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

openapi-generator-cli's Issues

[BUG] Cli does not work is the same as openapitool.json

๐Ÿ› Bug Report:

Describe the bug

Rune openapi-generator-cli failed on input globs

Steps to Reproduce

โฏ npx openapi-generator-cli generate -g typescript-angular -o "./libs/api/src/lib/generated/#{name}" -i "./libs/api/src/lib/*/api-*.yaml" -c "libs/api/openapi-config.json"
[error] Found unexpected parameters: [./libs/api/src/lib/api-one/api-one.yaml, ./libs/api/src/lib/api-two/api-two.yaml]

See 'openapi-generator-cli help' for usage.

Expected behavior

This is working if I use the openapitool.json file:

{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "4.3.1",
    "generators": {
      "v2.0": {
        "generatorName": "typescript-angular",
        "output": "./libs/api/src/lib/generated/#{name}",
        "glob": "./libs/api/src/lib/*/api-*.yaml",
        "additionalProperties": {
          "ngVersion": "11.2.2",
          "supportsES6": "true",
          "withInterfaces": true,
          "stringEnums": true,
          "modelNameSuffix": "Dto"
        }
      }
    }
  }
}

I expect the command line to work in the same way. It is finding the list of yaml files so the glob pattern is working.

It is also working if I specify one file

Ability to provide a hostname

I may be missing something, but is there really no way of providing an argument to set hostname to anything but localhost? (I am using the dart generator).

Currently my implementation is a node script that after generating the api loads the desired hostname from a .env file using dotenv, then finds and replaces the hostname in the file where it is specified. But this feels a bit overkill for such a common use case for these types of APIs.

Error when releasing 4.0.2

+ @openapitools/[email protected]
npm notice
npm notice ๐Ÿ“ฆ  @openapitools/[email protected]
npm notice === Tarball Contents ===
npm notice 768B   package.json
npm notice 11.4kB LICENSE
npm notice 3.0kB  README.md
npm notice 475B   bin/openapi-generator
npm notice 19.4MB bin/openapi-generator.jar
npm notice === Tarball Details ===
npm notice name:          @openapitools/openapi-generator-cli
npm notice version:       0.0.14-4.0.2
npm notice package size:  17.3 MB
npm notice unpacked size: 19.4 MB
npm notice shasum:        244394f7487a7744a267165828d3d5249842d2a7
npm notice integrity:     sha512-x4gKaGNgG5Eqt[...]28BIFuKPuFi5w==
npm notice total files:   5
npm notice
+ @openapitools/[email protected]
(node:16563) UnhandledPromiseRejectionWarning: ReferenceError: latestVersion is not defined
    at tagLatest (/private/tmp/openapi-generator-cli/bin/tag-latest:31:39)
    at Object.<anonymous> (/private/tmp/openapi-generator-cli/bin/tag-latest:32:3)
    at Module._compile (internal/modules/cjs/loader.js:734:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:745:10)
    at Module.load (internal/modules/cjs/loader.js:626:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:566:12)
    at Function.Module._load (internal/modules/cjs/loader.js:558:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:797:12)
    at executeUserCode (internal/bootstrap/node.js:526:15)
    at startMainThreadExecution (internal/bootstrap/node.js:439:3)
(node:16563) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16563) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
latest version (excluding beta) is set to 0.0.14-4.0.2
+latest: @openapitools/[email protected]

That's the error I got but seems like the latest release is still tagged correctly to 0.0.14-4.0.2 so we will look into this later as it's not something with the highest priority at the moment.

Trouble with Typescript-Axios and React

I receive the following error when installing the generated API as a module and attempting to run it.

../common/common.js 125:26
Module parse failed: Unexpected token (125:26)
File was processed with these loaders:
 * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|   return (axios = globalAxios, basePath = BASE_PATH) => {
|     const axiosRequestArgs = { ...axiosArgs.options,
>       url: (configuration?.basePath || basePath) + axiosArgs.url
|     };
|     return axios.request(axiosRequestArgs);

Folder Structure:

- /common
  - common.ts
  - common.js
  - package.json
  - tsconfig.json
- /web
  - src
  - package.json
  - tsconfig.json

Generation Config (Using OpenAPI v3 JSON):

{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "5.0.1",
    "generators": {
      "v1.0": {
        "generatorName": "typescript-axios",
        "output": "api/openapi/v1",
        "glob": "api/openapi/openapi.json",
        "additionalProperties": {
          "supportsES6": "true"
        }
      }
    }
  }
}

/common/tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "es2020",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

Steps to reproduce:

  1. Generate API
  2. tsc to transpile
  3. npm install ../common from /web
  4. npm start

[BUG] author template throws error on -g, Found unexpected parameters

๐Ÿ› Bug Report:

Describe the bug

openapi-generator-cli author template -g java --library webclient throws the error

[error] Found unexpected parameters: [-g, java, --library, webclient]

Steps to Reproduce

Steps to reproduce the behavior:

  1. Install >2.3.0
  2. Run openapi-generator-cli author template -g java --library webclient

Expected behavior

Extract templates
<2.3.0 appears to work fine?

Operation System (please complete the following information):

  • OS: OSX
  • Version Big Sur 14.4

Package System (please complete the following information):

  • Version 2.3.3
  • (5.1.1 of openapi jar)

Additional context

Perhaps an issue with the new minor feature addition?
custom generators: added '-custom-generator' parameter fixes #237 (99c2351)

Also reported in OpenAPI-Generator but it seems to be a cli issue?

The automated release is failing ๐Ÿšจ

๐Ÿšจ The automated release from the chore/setup-semantic branch failed. ๐Ÿšจ

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. Iโ€™m sure you can resolve this ๐Ÿ’ช.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the chore/setup-semantic branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those donโ€™t help, or if this issue is reporting something you think isnโ€™t right, you can always ask the humans behind semantic-release.


Missing package.json file.

A package.json file at the root of your project is required to release on npm.

Please follow the npm guideline to create a valid package.json file.


Good luck with your project โœจ

Your semantic-release bot ๐Ÿ“ฆ๐Ÿš€

Require docker image for ARM64

Hi Team,

I am checking on adding arm64 support in Travis-CI for the Open Service Broker API package. But I was facing an issue in pulling openapitools/openapi-generator-cli image for arm64 as it is not available in the docker hub. So I tried to build an openapi-generator-cli image locally on arm64 machine and found that 3.6.3-jdk-11-openj9 image is not available for arm64. So I replaced this image with 3.6.3-jdk-11 and I was successful in building an openapi-generator-cli docker image in my local arm64 machine.

If you are interested in uploading an arm64 image, I can raise a PR for the changes required to build an arm64 image. It will be very helpful if this image is available for the arm64 platform.

Cannot download openapi-generator when using Yarn2 PnP

Hello,

I seem to have an issue getting openapi-generator-cli to download openapi-generator when using Yarn PnP locally.

openapi-generator-cli fails to download openapi-generator because the directory it tries to write to is virtual. Yarn PnP unpacks zipped dependencies at runtime and therefore openapi-generator-cli cannot write to node_modules.

image

Maybe a way to set the download directory in some config could get around the issue? For now I have to use openapi-generator-cli from a global install.

Thanks

openapitools.json + generate error: requires option '-i'

Running openapi-generator-cli generate without additional parameter is not working: [error] Required option '-i' is missing

openapitools.json:

{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "5.0.0-beta2",
    "project-ts": {
        "generatorName": "typescript-axios",
        "output": "#{cwd}/src/api/#{name}",
        "glob": ".apiSchema/swagger/*.json"
    }
  }
}

package.json (excerpt):

"scripts": {
"generate:openapi": "openapi-generator-cli generate"
}
  • command: npm run generate:openapi in project root
  • valid openapi json in .apiSchema/swagger
  • CLI version: 2.0.2
  • Locally installed

npm warning `ERESOLVE overriding peer dependency`

When I have a package.json file like this:

{
  "name": "example",
  "version": "1.0.0",
  "description": "example",
  "keywords": [],
  "license": "MIT",
  "main": "index.js",
  "scripts": {},
  "devDependencies": {
    "@openapitools/openapi-generator-cli": "2.3.3"
  }
}

And I run npm i, I get the following output:

npm WARN ERESOLVE overriding peer dependency
npm WARN Found: [email protected]
npm WARN node_modules/rxjs
npm WARN   rxjs@"7.1.0" from @openapitools/[email protected]
npm WARN   node_modules/@openapitools/openapi-generator-cli
npm WARN     dev @openapitools/openapi-generator-cli@"2.3.3" from the root project
npm WARN 
npm WARN Could not resolve dependency:
npm WARN peer rxjs@"^6.0.0" from @nestjs/[email protected]
npm WARN node_modules/@nestjs/common
npm WARN   @nestjs/common@"7.6.17" from @openapitools/[email protected]
npm WARN   node_modules/@openapitools/openapi-generator-cli
npm WARN ERESOLVE overriding peer dependency
npm WARN Found: [email protected]
npm WARN node_modules/rxjs
npm WARN   rxjs@"7.1.0" from @openapitools/[email protected]
npm WARN   node_modules/@openapitools/openapi-generator-cli
npm WARN     dev @openapitools/openapi-generator-cli@"2.3.3" from the root project
npm WARN 
npm WARN Could not resolve dependency:
npm WARN peer rxjs@"^6.0.0" from @nestjs/[email protected]
npm WARN node_modules/@nestjs/core
npm WARN   @nestjs/core@"7.6.17" from @openapitools/[email protected]
npm WARN   node_modules/@openapitools/openapi-generator-cli

added 132 packages, and audited 133 packages in 20s

25 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

This wasn't the case with earlier versions (I can at least confirm this isn't the case with 2.2.6, but I didn't try any other versions).

I'm using the following:
NodeJS v15.10.0
npm 7.5.3

java-vertx generated code fails to run with nullpointerexception @ SwaggerRouter.getBasePath(SwaggerRouter.java:129)

Platform config:
OS: RHEL 7.8
Java: 11
openapi-generator-cli version: 4.1.2

I tried generating java-vertx code for a swagger-2 spec file and an openapi v3 spec file. Using below command
java -jar openapi-generator-cli.jar generate -g java-vertx -i ~/Documents/Work/swaggers\ for\ testing/Cards.yaml -o ~/GeneratedCode/openapi-java-vertx

Given swagger is correct without any issues. It opens jst fine on editor.swagger.io

Code was successfully generated. But had two issues

  1. In pom.xml vertx-swagger-router.version was empty, no provided
  2. After fixing above version, code failed to start with a nullpointerexception.

Stacktrace for pt.2

java.lang.NullPointerException
	at com.github.phiz71.vertx.swagger.router.SwaggerRouter.getBasePath(SwaggerRouter.java:129)
	at com.github.phiz71.vertx.swagger.router.SwaggerRouter.swaggerRouter(SwaggerRouter.java:75)
	at com.github.phiz71.vertx.swagger.router.SwaggerRouter.swaggerRouter(SwaggerRouter.java:70)
	at org.openapitools.server.api.MainApiVerticle.lambda$start$1(MainApiVerticle.java:50)
	at io.vertx.core.impl.FutureImpl.checkCallHandler(FutureImpl.java:188)
	at io.vertx.core.impl.FutureImpl.setHandler(FutureImpl.java:100)
	at io.vertx.core.impl.ContextImpl.lambda$null$0(ContextImpl.java:287)
	at io.vertx.core.impl.ContextImpl.lambda$wrapTask$2(ContextImpl.java:337)
	at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
	at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403)
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:445)
	at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
	at java.base/java.lang.Thread.run(Thread.java:834)

Inside MainApiVerticle.java are below line

FileSystem vertxFileSystem = vertx.fileSystem();
        vertxFileSystem.readFile("openapi.json", readFile -> {
            if (readFile.succeeded()) {
                Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
                Router swaggerRouter = SwaggerRouter.swaggerRouter(router, swagger, vertx.eventBus(), new OperationIdServiceIdResolver());

readFile() operation succeeds, however in next line value of swagger comes out as null. openapi.json was indeed present inside src/main/resources.
Please help.

[BUG]

Hi!
How I can keep original names in models?
Instead of '@odata.count' got odata_count
How can I fix it using openapi-generator-cli?

swagger JSON:
image
Axios typescript model interface with Odata:
image

Release a Semver compliant NPM version

Currently the version tag for openapi-generator-cli releases doesn't respect Semver (Semantic Versioning). For example the current release is 0.0.9-3.3.4.

I understand the rationale of being able to select both the CLI version and openapi-generator version at once but sadly this is inconsistent with the Semver convention.

As a first step, I'm proposing to add an extra published version which would only contain the cli version and would imply the latest openapi-generator release. This way we can keep the current versioning but users could also simply set the version to a semver version (for example: 0.0.9)

[BUG] not usable with private repository

๐Ÿ› Bug Report:

Describe the bug

Using openapi-generator-cli in a Jenkins based continuous integration without opened network route to outside, I can't use it because version-manager has hard-coded Nexus repo URL (https://repo1.maven.org/maven2/).

Steps to Reproduce

Steps to reproduce the behavior:

  1. Install openapi-generator-cli from npm repository (https://www.npmjs.com/package/@openapitools/openapi-generator-cli)
  2. Execute openapi-generator-cli through a NPM script

Expected behavior

Have a mean to specify a private Nexus repo instead of central one.

[BUG]

โš ๏ธ Important Notice

Please differentiate the bug

This repository is not responsible for the actual code generation. If you have problems with the code generation, please open the bug at OpenAPITools/openapi-generator.

Please also check if the bug is already known before you open a new bug.


๐Ÿ› Bug Report:

Describe the bug

A clear and concise description of what the bug is.

Steps to Reproduce

Steps to reproduce the behavior:

  1. npx create-strapi-app my-app --quickstart
  2. cd my-app
  3. yarn strapi install documentation
  4. code extensions/documentation/documentation/1.0.0/full_documentation.json``
  5. ctrl+f
  6. =
  7. You should be able to see a section similar to
          {
            "name": "=",
            "in": "query",
            "required": false,
            "description": "Get entries that matches exactly your input",
            "schema": {
              "type": "string"
            },
            "deprecated": false
          },
  1. mkdir client
  2. npx openapi-generator-cli generate -i extensions/documentation/documentation/1.0.0/full_documentation.json -g typescript-fetch -o client --additional-properties=typescriptThreePlus=true --skip-validate-spec
  3. code client/apis/UsersPermissionsUserApi.ts
  4. :113 (Around the line 113 there should be a syntax error)
        if (requestParameters. !== undefined) {
            queryParameters['&#x3D;'] = requestParameters.;
        }

Expected behavior

The following code is generated instead

        if (requestParameters['='] !== undefined) {
            queryParameters['&#x3D;'] = requestParameters['='];
        }

Screenshots

Screenshot from 2021-01-04 16-08-34

Screenshot from 2021-01-04 16-07-54

Operation System (please complete the following information):

  • OS: Ubuntu
  • Version: 20.04

Package System (please complete the following information):

  • Version: ^2.1.16

Additional context

Add any other context about the problem here.

The automated release is failing ๐Ÿšจ

๐Ÿšจ The automated release from the master branch failed. ๐Ÿšจ

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. Iโ€™m sure you can resolve this ๐Ÿ’ช.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those donโ€™t help, or if this issue is reporting something you think isnโ€™t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org.


Good luck with your project โœจ

Your semantic-release bot ๐Ÿ“ฆ๐Ÿš€

NPM package with jar already embedded

The version manager and ability to select which version of the openapi-generator jar to use is nice. However, it presumes every development environment has unfettered internet access that allows openapi-generator-cli to access the hardcoded URLs for search and download. This isn't always the case.

It would be convenient for the internet impaired to have a released NPM package that bundles the latest stable jar so the cli can just run out of the box without additional download.

I'm sure the jar can be downloaded separately and dropped into a directory to prevent the download. This means I have to manually manage the dependencies of my NPM dependencies which doesn't seem ideal.

[BUG] Spec source from `inputSpec` is ignored

๐Ÿ› Bug Report:

Describe the bug

Property inputSpec is ignored, which makes using remote specs impossible. According to the json schema this should be supported:

"inputSpec": {
          "type": "string",
          "description": "location of the OpenAPI spec, as URL or file (required if not loaded via config using -c)"
        },

https://github.com/OpenAPITools/openapi-generator-cli/blob/master/apps/generator-cli/src/config.schema.json

Expected behavior

Defining an HTTP URL to a remote spec via inputSpec should be possible.

Additional context

The method generate in generator.service.ts ignores the inputSpec property and only considers glob.

additional-properties serialization example/documentation

I am looking for (and am willing to make a PR) documenting the correct way to submit multiple additional properties to @openapitools/openapi-generator-cli from an npm script.

The example in the readme for using additional-properties only illustrates using a single property.

"my-awesome-script-name": "openapi-generator generate -i docs/openapi.yaml -g typescript-angular -o generated-sources/openapi --additional-properties=\"ngVersion=6.1.7\""

Could I get an example of an array of additional properties being used?
I will be happy to make a pr enhancing the example in the readme once I know what is required.

I would like to pass multiple properties defined in my generator type.

Examples of serialization issues experienced:

[error] Found unexpected parameters: [npmName=restClient,, supportsES6=true,, npmVersion=6.9.0,, withInterfaces=tr
ue]

"my-awesome-script-name": "openapi-generator generate -i docs/openapi.yaml -g typescript-angular -o generated-sources/openapi --additional-properties="ngVersion=6.1.7 npmName=restClient supportsES6=true npmVersion=6.9.0 withInterfaces=true"
Results in:

[error] Found unexpected parameters: [npmName=restClient, supportsES6=true, npmVersion=6.9.0, withInterfaces=true]

Could someone post an example of what additional-properties is expecting here?

Additional info:
The java tests around this seem to be expecting a map:
https://github.com/OpenAPITools/openapi-generator/blob/046db19a8590f3557ae1e04be75792bbeb39cb69/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularAdditionalPropertiesIntegrationTest.java#L36

List of keys we should be able to access from additional-properties:
https://openapi-generator.tech/docs/generators/typescript-angular

I have also tried using -p instead of --additional-properties as per the docs and got the same results above.

Edit: It appears the whitespace is important for the additional-properties keys.
This works for me:

"my-awesome-script-name": "openapi-generator generate -i docs/openapi.yaml -g typescript-angular -o generated-sources/openapi --additional-properties=ngVersion=6.1.7,npmName=restClient,supportsES6=true,npmVersion=6.9.0,withInterfaces=true"

I can make a pr that adds an example like this to the readme, that will hopefully save other developers a few hours of debugging.

[BUG] Self signed certificate issue

๐Ÿ› Bug Report:

Describe the bug

After installing openapi generator, when try to use it has self signed certificate issue

Steps to Reproduce

Steps to reproduce the behavior:

  1. Install open api
    npm install -g @openapitools/openapi-generator-cli
  2. run openapi-generation-cli version or any other command

Expected behavior

See the version of the generaton

Screenshots

If applicable, add screenshots to help explain your problem.
image

Operation System (please complete the following information):

  • OS: windows
  • Version 10

Package System (please complete the following information):

  • Version latest

Additional context

I am inside corporate network

Where can I find changelog/version history/tags to decide to upgrade or not?

Running npm outdated it makes me aware that a new openapi-generator-cli version is available:

$ npm outdated
Package                                   Current        Wanted        Latest
@openapitools/openapi-generator-cli  1.0.13-4.3.1  1.0.13-4.3.1  1.0.15-4.3.1

I couldn't find any tags in this repository to check what has changed since the version that I am currently using (1.0.13-4.3.1).

What's the best way to see this package's version history so I can make a decision on updating to latest version or not?

Problems with SSL certificate

Hi,

I try to use this CLI in my project to generate my API typescript client. But my swagger.yaml file is on a https url and I have errors because of SSL certificate.

I added the following script to my package.json :

"swagger": "./node_modules/.bin/openapi-generator generate -i https://myserver/api-docs -g typescript-fetch -o src/services/Api/swagger"

But when I run npm swagger I have the followin stack trace :

[main] ERROR i.s.parser.SwaggerCompatConverter - failed to read resource listing                                                                                                                                                                                                javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target                                                      at sun.security.ssl.Alerts.getSSLException(Unknown Source)                                                                                                                                                                                                                      
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)                                                                                                                                                                                                                         
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)                                                                                                                                                                                                                          
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)                                                                                                                                                                                                                          
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)                                                                                                                                                                                                          
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)                                                                                                                                                                                                             
at sun.security.ssl.Handshaker.processLoop(Unknown Source)                                                                                                                                                                                                                      
at sun.security.ssl.Handshaker.process_record(Unknown Source)                                                                                                                                                                                                                   
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)                                                                                                                                                                                                                    
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)                                                                                                                                                                                                       
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)                                                                                                                                                                                                                
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)                                                                                                                                                                                                                
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)                                                                                                                                                                                                          
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)                                                                                                                                                                                        
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)                                                                                                                                                                                                    
at io.swagger.parser.util.RemoteUrl.urlToString(RemoteUrl.java:134)                                                                                                                                                                                                             
at io.swagger.parser.SwaggerCompatConverter.readResourceListing(SwaggerCompatConverter.java:193)                                                                                                                                                                                
at io.swagger.parser.SwaggerCompatConverter.read(SwaggerCompatConverter.java:123)                                                                                                                                                                                               
at io.swagger.parser.SwaggerCompatConverter.readWithInfo(SwaggerCompatConverter.java:94)                                                                                                                                                                                        
at io.swagger.parser.SwaggerParser.readWithInfo(SwaggerParser.java:42)                                                                                                                                                                                                          
at io.swagger.v3.parser.converter.SwaggerConverter.readLocation(SwaggerConverter.java:92)                                                                                                                                                                                       
at io.swagger.parser.OpenAPIParser.readLocation(OpenAPIParser.java:19)                                                                                                                                                                                                          
at org.openapitools.codegen.config.CodegenConfigurator.toClientOptInput(CodegenConfigurator.java:606)                                                                                                                                                                           
at org.openapitools.codegen.cmd.Generate.run(Generate.java:367)                                                                                                                                                                                                                 
at org.openapitools.codegen.OpenAPIGenerator.main(OpenAPIGenerator.java:60)                                                                                                                                                                                             Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target                                                                                at sun.security.validator.PKIXValidator.doBuild(Unknown Source)                                                                                                                                                                                                                 
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)                                                                                                                                                                                                          
at sun.security.validator.Validator.validate(Unknown Source)                                                                                                                                                                                                                    
at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)                                                                                                                                                                                                               
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)                                                                                                                                                                                                           
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)                                                                                                                                                                                                     ... 21 common frames omitted                                                                                                                                                                                                                                            
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target                                                                                                                                                      
at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)                                                                                                                                                                                                      
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)                                                                                                                                                                                                
at java.security.cert.CertPathBuilder.build(Unknown Source)                                                                                                                                                                                                                     
... 27 common frames omitted                                                                                                                                                                                                                                            
Exception in thread "main" java.lang.NullPointerException                                                                                                                                                                                                                               
at java.util.HashSet.(Unknown Source)                                                                                                                                                                                                                                     
at org.openapitools.codegen.config.CodegenConfigurator.toClientOptInput(CodegenConfigurator.java:608)                                                                                                                                                                           
at org.openapitools.codegen.cmd.Generate.run(Generate.java:367)                                                                                                                                                                                                                 
at org.openapitools.codegen.OpenAPIGenerator.main(OpenAPIGenerator.java:60)
--

Any idea how I could solve this ?

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Non-value CLI flags are not translated correctly

I've set up a generator config in openapitools.json with "skipValidateSpec": true, and just ran openapi-generator-cli generate. Unfortunately, this (and other non-value) flag is translated to --skip-validate-spec=true, but should be --skip-validate-spec. The client fails with:

[[angular] openapi_solve.yml] [error] Found unexpected parameters: [--skip-validate-spec=true]
[[angular] openapi_solve.yml] 
[[angular] openapi_solve.yml] See 'openapi-generator-cli help' for usage.

I'm not sure if this is a regression with the release of a new CLI version, but we should add exclusions in the generator for these flags.

[BUG] Multiple openapi-generator-cli processeses may download jar to corrupt file

๐Ÿ› Bug Report:

Describe the bug

When multiple node processes execute openapi-generator-cli, and multiple node processes download the openapi-generator jar file, it may become corrupt.

Steps to Reproduce

Steps to reproduce the behavior:

  1. Execute 2 or more node processes that execute openapi-generator-cli
  2. If they both detect that the openapi-generator jar should be downloaded, both will do so simultaneously, to the same location.
  3. Both processes write to the same file, and it may become corrupt.

Expected behavior

There should not be any file corruption, and also not any errors.

You may use a file lock, or download it to a temporary location and move it atomically to the correct location after downloading.

Screenshots

Excerpt of openapi-generator-cli downloading the jar file.

Download 5.0.0-beta2 ...                                                                                                                                                     
(node:18698) UnhandledPromiseRejectionWarning: Error: Error: Invalid or corrupt jarfile /home/hidde.wieringa/Projects/api/node_modules/@openapitools/openapi-generator-cli/ve
rsions/5.0.0-beta2.jar                                                                                                                                                       
                                                                                                                                                                             
    at /home/hidde.wieringa/Projects/api/node_modules/@openapitools/openapi-generator-cli/main.js:613:32                                                                     
    at ChildProcess.exithandler (child_process.js:315:5)                                                                                                                     
    at ChildProcess.emit (events.js:315:20)                                                                                                                                  
    at maybeClose (internal/child_process.js:1048:16)                                                                                                                        
    at Socket.<anonymous> (internal/child_process.js:439:11)                                                                                                                 
    at Socket.emit (events.js:315:20)                                                                                                                                        
    at Pipe.<anonymous> (net.js:673:12)                                                                                                                                      
(Use `node --trace-warnings ...` to show where the warning was created)                                                                                                      
(node:18698) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by
 rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see
 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)                                                                                           
(node:18698) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js pro
cess with a non-zero exit code.                                                                                                                                              
Downloaded 5.0.0-beta2                                                                                                                                                       
[main] INFO  o.o.codegen.DefaultGenerator - Generating with dryRun=false                                                                                                     

Operation System (please complete the following information):

  • Debian 10

Package System (please complete the following information):

  • 1.0.18-5.0.0-beta2
  • Yarn workspaces is in use

Additional context

Update npm version from 4.0.0-beta3 to 4.0.0

Given that 4.0.0 was released 15 days ago and npm release was done 14 days ago I am assuming this happend by mistake. It would be awesome if you could update the release. Thanks a ton!

[BUG] String type parameter in post request body was generated as Java class type

used cli to create a client sdk jar file: java -jar openapi-generator-cli-5.0.0-beta3.jar generate --input-spec synopsys-coverity-coverity-connect-2020.12-resolved.yaml -g java -o connectAPIclient-2020.12 .

in the swagger yaml file, two String parameters (FilterKey and FilterMatchMode )were defined in the post request body. the only difference is FilterMatchMode is a enum string, it only allows two values ("oneOrMoreMatch" or "noneMatch"), but in the auto Generated java code, the FilterKey was generated as a string type, but FilterMatchMode was generated as a FilterMatchMode class type, both should be generated as String type.

Swagger definition:
`

FilterKey string

FilterMatchMode string
values:
oneOrMoreMatch: (Default) At least one of the values must match the item.
noneMatch: None of the values may match the item.
Enum:[ย oneOrMoreMatch, noneMatchย ]

Auto generated JAVA code: ย @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2020-12-12T03:14:15.736Z[GMT]")
public class FilterElement {
@SerializedName("filterKey")
private String filterKey = null;

@SerializedName("matchMode")
private FilterMatchMode matchMode = null;
`

[Feature request]: Add Readme instructions to have JDK installed

Report:

Describe the bug

error when trying to generate clients using the npx module.

npx @openapitools/openapi-generator-cli generate -g ruby -i https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -o /var/tmp/ruby-client
(node:33270) UnhandledPromiseRejectionWarning: Error: No Java runtime present, requesting install.

Can't load config class with name 'typescript-axios'

In version 0.0.8-3.2.0 I got this error.
How can I use typescript-axios generator?

Can't load config class with name 'typescript-axios'
Available:
ada
ada-server
android
apache2
apex
aspnetcore
bash
clojure
cwiki
cpp-qt5
cpp-qt5-qhttpengine-server
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-flowtyped
javascript-closure-angular
jmeter
lua
nodejs-server
objc
openapi
openapi-yaml
perl
php
php-laravel
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

[error] Check the spelling of the generator's name and try again.
npm ERR! code ELIFECYCLE
npm ERR! errno 1

--import-mappings not working for Go

I am runing below command to use my own type "CustomDateTime" defined in "config" package and not to use time.Time
in generated models.

openapi-generator-cli generate -g go-experimental -i api-docs.json -o ${CLIENTPATH} --import-mappings=config.CustomDateTime=myProject/config --type-mappings=time.Time=config.CustomDateTime

with this , i can see my struct got the "config.CustomDateTime" as datatype instead of time.Time, however it didnt added the import statement & hence there is compilation error in go file.

package hybris

type Cart struct {
CreationTime *config.CustomDateTime json:"creationTime,omitempty"
}

why the import-mappings is not working for go-experimental/go ?

there are releases on npm that or not on github

as the title says, there are new releases on npm that or not visible on github and there is also no changelog/history suggesting anything changed. Looking at the commits, it is to a certain point visible but the release 1.0.18-4.3.1 comes with absolute no context. What is the reason for this?

Version-Manager does not work with cygwin

I just updated the openapi-generator-cli at our project to version 2.0.3 including the new version manager. I use windows with cygwin and the generated openapitools.json is not generated and located at the working-directory of the project.
I searched the system and found the file located under C:\cygdrive\c\path\to\my\project instead of C:\path\to\my\project or from the cygwin-point-of-view at /cygdrive/c/path/to/my/project.

Can you please fix this so I can use the version-manager with cygwin?

openapi-generator.jar corrupt (v1.0.9 packages)

Latest 1.0.9 packages appear to have an issue with the jar from maven:

Repro steps:

> npm i @openapitools/[email protected] -g
> openapi-generator

Output:
Error: Invalid or corrupt jarfile C:\...\npm\node_modules\@openapitools\openapi-generator-cli\bin\openapi-generator.jar

This file:
node_modules\@openapitools\openapi-generator-cli\bin\openapi-generator.jar

Contains an http redirect message:

<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
</body>
</html>

How to add Bearer token to headers after login

I successfully generated the api methods from our swagger.json file for our React application.

But there is no example how to set Authorization headers (Bearer token) after a successful login.

For example:

new Api.UserManagementApi({
  headers: ...
});

Or:

const configuration = new Api.Configuration();
configuration.headers.set('Authorization', 'Bearer ' + token);

[BUG] Download of openapi-generator client not possible behind corporate firewall

๐Ÿ› Bug Report:

Describe the bug

Request fails with status code 500 when trying to install behind a corporate firewall.

Steps to Reproduce

  1. Block internet if connection does not go through proxy

Expected behavior

Jar will be downloaded correctly

Screenshots

If applicable, add screenshots to help explain your problem.

grafik

Operation System (please complete the following information):

  • OS: Windows 10
  • Version 1809 (Build 17763.1697)

Package System (please complete the following information):

  • NPM Version 6.14.8

[missing feature] custom generators on classpath are not visible

Custom generators are not visible to openapi-generator

Custom generators can be shipped as .jar file with codegen config and templates. This works fine with maven/gradle plugins, just add the .jar with a custom generator to dependencies. However, this will not work with openapi-generator-cli because generator .jar is called using -jar option. When java is started with -jar option, then -cp (classpath) option is ignored.

A solution to this could be use of class path and main class explicitly

  java -cp "${userProvidedClasspath}:${this.versionManager.filePath()}" org.openapitools.codegen.OpenAPIGenerator ...

This will work the same as with -jar option, but provides the user with an option to declare custom generator.

Steps to Reproduce

  1. Make a new custom generator
  2. Add script to package.json with JAVA_OPTS='-cp custom-generator.jar' openapi-generator-cli list
  3. You will not see the generator because -cp option is ignored

Expected behavior

A mechanism to add custom .jar files to classpath. This will make it possible to ship custom generator as a .jar file.

I can make a pull request with this fix if you approve this idea. PassThroughService can simply check if class path extensions are provided. If not, then run generator with -jar option. Otherwise, assemble class path and run main class directly.

[BUG] setting cli arguments causes config file to be ignored

โš ๏ธ Important Notice

Please differentiate the bug

This repository is not responsible for the actual code generation. If you have problems with the code generation, please open the bug at OpenAPITools/openapi-generator.

Please also check if the bug is already known before you open a new bug.


๐Ÿ› Bug Report:

Describe the bug

you cant seem to mix a config file with some of the cli options.
In this case I'm trying to set --server-variables=major=2 as the version is determined via script

Steps to Reproduce

Steps to reproduce the behavior:

Config File:

{
  "$schema": "../../node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "5.1.1",
    "generators": {
      "server": {
        "generatorName": "aspnetcore",
        "output": "#{cwd}/../.generated",
        "glob": "src/*.{json,yaml,yml}",
        "modelNameSuffix": "",
        "apiNameSuffix": "Base",
        "additionalProperties": {
          "aspnetCoreVersion": "5.0",
          "classModifier": "abstract",
          "buildTarget": "library",
          "isLibrary": true,
          "packageName": "OpenApi.Generated",
          "operationIsAsync": true,
          "operationResultTask": true,
          "operationModifier": "abstract",
          "swashbuckleVersion": "5.0.0"
        }
      }
    }
  }
}

running openapi-generator-cli generate woks as expected

running openapi-generator-cli generate --server-variables=major=2 errors with:
[error] Required option '-i' is missing

running openapi-generator-cli generate --server-variables=major=2 --config=openapitools.json errors with:

Exception in thread "main" java.lang.NullPointerException: generator name must be specified
        at org.apache.commons.lang3.Validate.notEmpty(Validate.java:395)
        at org.openapitools.codegen.config.CodegenConfigurator.toContext(CodegenConfigurator.java:482)
        at org.openapitools.codegen.config.CodegenConfigurator.toClientOptInput(CodegenConfigurator.java:573)
        at org.openapitools.codegen.cmd.Generate.execute(Generate.java:433)
        at org.openapitools.codegen.cmd.OpenApiGeneratorCommand.run(OpenApiGeneratorCommand.java:32)
        at org.openapitools.codegen.OpenAPIGenerator.main(OpenAPIGenerator.java:66)

Expected behavior

The cli should use the settings in the config file, with any cli arguments added/overriding the values in the file

Operation System (please complete the following information):

  • OS: Ubuntu
  • Version 20

Package System (please complete the following information):

  • npm 6.14.13

RuntimeException: Could not generate model 'AddressBodySchema'

Hello!

So I'm running:

docker run --rm     --user $(id -u):$(id -g)     openapitools/openapi-generator-cli:v4.3.0 validate     -i https://raw.githubusercontent.com/omgnetwork/elixir-omg/master/apps/omg_watcher_rpc/priv/swagger/security_critical_api_specs.yaml
Validating spec (https://raw.githubusercontent.com/omgnetwork/elixir-omg/master/apps/omg_watcher_rpc/priv/swagger/security_critical_api_specs.yaml)
No validation issues detected.
docker run --rm     --user $(id -u):$(id -g)     openapitools/openapi-generator-cli:v4.3.0 generate     -i https://raw.githubusercontent.com/omgnetwork/elixir-omg/master/apps/omg_watcher_rpc/priv/swagger/security_critical_api_specs.yaml     -g elixir     -o apps/watcher_security_critical_api/
[main] INFO  o.o.codegen.DefaultGenerator - Generating with dryRun=false
[main] WARN  o.o.c.ignore.CodegenIgnoreProcessor - Output directory does not exist, or is inaccessible. No file (.openapi-generator-ignore) will be evaluated.
[main] INFO  o.o.codegen.DefaultGenerator - OpenAPI Generator: elixir (client)
[main] INFO  o.o.codegen.DefaultGenerator - Generator 'elixir' is considered stable.
[main] INFO  o.o.codegen.AbstractGenerator - writing file /apps/watcher_security_critical_api/lib/watcher_security_critical_api/model/address_body_schema.ex
Exception in thread "main" java.lang.RuntimeException: Could not generate model 'AddressBodySchema'
	at org.openapitools.codegen.DefaultGenerator.generateModels(DefaultGenerator.java:539)
	at org.openapitools.codegen.DefaultGenerator.generate(DefaultGenerator.java:1005)
	at org.openapitools.codegen.cmd.Generate.run(Generate.java:426)
	at org.openapitools.codegen.OpenAPIGenerator.main(OpenAPIGenerator.java:61)
Caused by: java.nio.file.NoSuchFileException: /apps/watcher_security_critical_api/lib/watcher_security_critical_api/model/address_body_schema.ex
	at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
	at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
	at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
	at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
	at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434)
	at java.nio.file.Files.newOutputStream(Files.java:216)
	at java.nio.file.Files.write(Files.java:3292)
	at org.openapitools.codegen.AbstractGenerator.writeToFileRaw(AbstractGenerator.java:111)
	at org.openapitools.codegen.AbstractGenerator.writeToFile(AbstractGenerator.java:96)
	at org.openapitools.codegen.DefaultGenerator.writeToFile(DefaultGenerator.java:1513)
	at org.openapitools.codegen.AbstractGenerator.writeToFile(AbstractGenerator.java:57)
	at org.openapitools.codegen.DefaultGenerator.processTemplateToFile(DefaultGenerator.java:1080)
	at org.openapitools.codegen.DefaultGenerator.generateModel(DefaultGenerator.java:384)
	at org.openapitools.codegen.DefaultGenerator.generateModels(DefaultGenerator.java:530)
	... 3 more

The stacktrace isn't very informative. Any hints how to debug this? Could this be an issue with the CLI?

Create a JS API for openapi-generator

It would be nice to be able to do something like

const {openapi} = require('openapi-generator');
await openapi.generate(language: 'java', input: 'http://openapi.yml', configOptions: ...);

[BUG] json configuration is ignored

๐Ÿ› Bug Report:

Describe the bug

openapitools.json is ignored

Steps to Reproduce

  1. Place any spec in file api.yaml
  2. configure openapitools.json as following
{
  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
  "spaces": 2,
  "generator-cli": {
    "version": "4.3.1",
    "v3.0": { 
      "glob": "api.yaml",
      "generatorName": "typescript-fetch",
      "output": "#{cwd}/src/api",
      "additionalProperties": {
        "typescriptThreePlus": true

      }
    }
  }
}
  1. yarn add --dev @openapitools/openapi-generator-cli
  2. yarn openapi-generator-cli generate
  3. "[error] Required option '-i' is missing"

Expected behavior

api.yaml is used to generate spec

Operation System:

  • OS: Ubuntu
  • Version 20.04

Package System:

  • yarn
  • Version 1.22.5

[BUG][typescript-axios] For nested fields there is `& AnyType` generated

๐Ÿ› Bug Report:

Describe the bug

Whenever there is nested object defined in request body there is & AnyType added to actuall type of nested field. When I'm trying to build api client I get following error:

api.ts:767:36 - error TS4033: Property 'createdAt' of exported interface has or is using private name 'AnyType'.

767     createdAt?: DateRangeRequest & AnyType;

Steps to Reproduce

Steps to reproduce the behavior:

  1. Create swagger request body definition that has nested fields
  2. run openapi-generator-cli generate
  3. Check generated api.ts for & AnyType occurance
  4. Build api client
  5. See build error Property 'your_prop' of exported interface has or is using private name 'AnyType'.

Expected behavior

There shouldn't be & AnyType added to api.ts

Screenshots

image

Operation System (please complete the following information):

  • OS: Ubuntu
  • Version 20.04

Package System (please complete the following information):

  • Version 2.1.7

Additional context

I found this issue in main openapi generator OpenAPITools/openapi-generator#6332. It seems like it was resolved in openapi-generator but not applied on this npm wrapper.

prevent jar from being downloaded everytime when generating

Great work with the 5.0.0 release and all its improvements!

I noticed that the jar is being downloaded everytime I run npx @openapitools/[email protected] generate -i api.yml? Given that the version is "hardcoded" into the config.yml that is generated on first-run, it is unclear to me why it needs to download the jar every time. I saw I can download the jar file separately but didnt find a way how to pass the jar location to the openapi-generator-cli.

Did I overlook the documentation?

[BUG] Version Manager does not wait for the writeStream to end before resolving download

๐Ÿ› Bug Report:

Describe the bug

Sometimes, running on CI (Jenkins), the generator fails because Java throws an error saying that the jar file in invalid while it is valid.

(node:61381) UnhandledPromiseRejectionWarning: Error: Error: Invalid or corrupt jarfile /my/jenkins/job/workspace
at Object (/my/jenkins/job/workspacenode_modules/@openapitools/openapi-generator-cli/main.js:613:32)
    at ChildProcess.exithandler (child_process.js:296:5)
    at ChildProcess.emit (events.js:182:13)
    at maybeClose (internal/child_process.js:962:16)
    at Socket.stream.socket.on (internal/child_process.js:381:11)
    at Socket.emit (events.js:182:13)
    at Pipe._handle.close (net.js:606:12)

This issue seems to happen because, when the VersionManagerService downloads the .jar file, the download method waits for the download stream to end to resolve while it does not wait for the write stream to end. So the generator launches the java process while the .jar file it is still incomplete and java throws this error.
If I download the so called incomplete file on my local machine, its works perfectly and if i launch again my jenkins job without clearing the workspace, the generator does not fail.

Package System (please complete the following information):

  • Node v10.13.0
  • Jenkins v2.60.3
  • Java JDK 1.8

Additional context

I notice this issue on CI and not on my local machine. I suppose that it could also appear there but since the job is launched many times in CI during the day, cleans the workspace on each build and my jenkins machine is way faster than my local one, i have less chances to notice it on my local machine too.

Based on the Node JS - fs documentation, here is a proposal. I'm sorry, i didn't setup my workspace for this project :

  // apps/generator-cli/src/app/services/version-manager.service.ts
 async download(versionName: string) {
    // [...]

    try {
      await this.httpService
        .get<Stream>(downloadLink, { responseType: 'stream' })
        .pipe(switchMap(res => new Promise(resolve => {
            fs.ensureDirSync(this.storage);
            const file = fs.createWriteStream(filePath);
            res.data.pipe(file);
            // previous code 
            // res.data.on('end', resolve);
            // new code 
            file.on('finish', resolve);
          })
        )).toPromise();
   // [...]
  }

Method with Path variable

Hello, i have problem with API, where is defined method with path variable (in case where given variable is defined via $ref). When i try generate code according to API, then is result following:
-attribute paths.'/user/{idAccount}'. Declared path parameter idAccount needs to be defined as a path parameter in path or operation level

...
  /user/{idAccount}/baseInfo:
    parameters:
      - $ref: "#/components/parameters/TrackingCallId"
      - $ref: "#/components/parameters/idAccount"
    post:
      tags:
        - "User"
      summary: "Create user"
      description: "Method to create user for given customer"
      operationId: "createUser"
...
components:
  parameters:
    idAccount:
      name: "idAccount"
      in: "path"
      required: true
      description: "Identification of CRM customer"
      schema:
        type: string

best regards - jt -

[Support] How to use open api generator cli in monorepo architecture (Nrwl/nx)

After some investigation, I have some difficulties to setup openapi-generator-cli in a monorepo architecture.

Goal: Generate the API only for a specific project

  • I tried to duplicate openapitool.json in each project but I didn't find a way to provide the path of the file when running the command. Only next to the package.json ?
  • Could be a generator key inside a global openapitool.json but I didn't find a way to provide the generator key of the file when running the command. Only for console logging ?
  • I tried to customize the input of a command but #334

I am working in a Nrwl/Nx architecture like this project. Do you think a builder would be justified in this repository ?

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.