openapi-json-schema-tools / openapi-json-schema-generator

OpenAPI JSON Schema Generator allows auto-generation of API client libraries with a focus on JSON schema given an OpenAPI document
Apache License 2.0
150 stars 15 forks source link
code-generation draft2020-12 draft5 hacktoberfest hacktoberfest2022 help-wanted java json-schema jsonschema kotlin openapi openapi-generator openapi-specification openapi3 openapi31 python python3 rest schema-validation

OpenAPI JSON Schema Generator

CI Tests Apache 2.0 License

Auto generate a client sdk from your openapi 3.0.0-3.1.0 document using Openapi JSON Schema Generator. This project is a code generator that focuses on supporting all openapi and json schema features.

Overview

OpenAPI JSON Schema Generator allows auto-generation of API client libraries (SDK generation) given an OpenAPI document (3.0.0-3.1.0* are supported). This project focuses on making the output 100% compliant with openapi + JSON schema specs. The goal is to fully support everything defined in openapi + the included JSON schema specs so developers can use all of those features.

Currently, the following languages/frameworks are supported:

Feature Python Java Kotlin
Generator status stable stable stable
Openapi v3.0.0-3.1.0 ingestion X X X
Json Schema 2020-12 Support (components/schemas) X X X
Component schema classes + documentation produced X X X
Documentation produced for other component types:
headers, parameters, requestBodies, ressponses, securitySchemes
X X
Methods generated for endpoints
that send/receive json + docs generated for them
X X

Reasons To Use the Generators

Join Our Community

We use a Discord server as a place to ask questions and help each other. It offers functionality very similar to Slack. You can join us here: https://discord.gg/mHB8WEQuYQ

Can I build here?

Yes; contributions are welcome! Submit a PR if you want to add a new server scaffold, client sdk, or documentation generator in any language.

Table of contents

Installation

Compatibility

The OpenAPI Specification has undergone 3 revisions since initial creation in 2010. The openapi-json-schema-generator project has the following compatibilities with the OpenAPI Specification:

OpenAPI JSON Schema Generator Version OpenAPI Spec compatibility
3.3.0+ 3.0.0 - 3.1.0*
3.1.0 - 3.2.1 3.0.0 - 3.1.0
1.0.0 - 3.0.0 3.0.0 - 3.0.3

OpenAPI v3.1.0 support

OpenAPI v3.1.0 specification support includes these new/updated 2020-12 json schema keywords:

  1. const: only string values are working because of bugs in swagger parser
  2. contains
  3. dependentRequired
  4. dependentSchemas
  5. else
  6. if
  7. maxContains
  8. minContains
  9. patternProperties
  10. prefixItems
  11. propertyNames
  12. then
  13. type (array of types supported in addition to one non-array value)
  14. unevaluatedItems
  15. unevaluatedProperties

Note: these features can also be seen in the generator documentation schema features

Build Projects

To build from source, you need the following installed and available in your $PATH:

After cloning the project, you can build it from source with this command:

mvn clean install

The default build contains minimal static analysis (via CheckStyle). To run your build with PMD and Spotbugs, use the static-analysis profile:

mvn -Pstatic-analysis clean install

Docker

Public Pre-built Docker images

OpenAPI JSON Schema Generator CLI Docker Image

The docker image acts as a standalone executable. It can be used as an alternative to installing via homebrew, or for developers who are unable to install Java or upgrade the installed version.

To generate code with this image, you'll need to mount a local location as a volume.

Example:

docker run --rm -v "${PWD}:/local" openapijsonschematools/openapi-json-schema-generator-cli generate \
    -i https://raw.githubusercontent.com/openapi-json-schema-tools/openapi-json-schema-generator/master/src/test/resources/3_0/petstore.yaml \
    -g python \
    -o /local/out/python

The generated code will be located under ./out/python in the current directory.

Development in docker

You can use bin/run-in-docker.sh to do all development. This script maps your local repository to /gen in the docker container. It also maps ~/.m2/repository to the appropriate container location.

To execute mvn package:

git clone https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
cd openapi-json-schema-generator
./bin/run-in-docker.sh mvn package

Build artifacts are now accessible in your working directory.

Once built, run-in-docker.sh will act as an executable for openapi-json-schema-generator-cli. To generate code, you'll need to output to a directory under /gen (e.g. /gen/out). For example:

./bin/run-in-docker.sh help # Executes 'help' command for openapi-json-schema-generator-cli
./bin/run-in-docker.sh list # Executes 'list' command for openapi-json-schema-generator-cli
./bin/run-in-docker.sh /gen/bin/python-petstore.sh  # Builds the Python client
./bin/run-in-docker.sh generate -i src/test/resources/3_0/petstore.yaml \
    -g go -o /gen/out/python-petstore -p packageName=petstore_api # generates python client, outputs locally to ./out/python-petstore
Troubleshooting

If an error like this occurs, just execute the mvn clean install -U command:

org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project openapi-json-schema-generator: A type incompatibility occurred while executing org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test: java.lang.ExceptionInInitializerError cannot be cast to java.io.IOException

./run-in-docker.sh mvn clean install -U

Failed to execute goal org.fortasoft:gradle-maven-plugin:1.0.8:invoke (default) on project openapi-json-schema-generator-gradle-plugin-mvn-wrapper: org.gradle.tooling.BuildException: Could not execute build using Gradle distribution 'https://services.gradle.org/distributions/gradle-4.7-bin.zip'

Right now: no solution for this one :|

Getting Started

To generate a python client for petstore.yaml, please run the following

git clone https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
cd openapi-json-schema-generator
mvn clean package
java -jar target/openapi-json-schema-generator-cli.jar generate \
   -i https://raw.githubusercontent.com/openapi-json-schema-tools/openapi-json-schema-generator/master/src/test/resources/3_0/petstore.yaml \
   -g python \
   -o /var/tmp/python_api_client

(if you're on Windows, replace the last command with java -jar target\openapi-json-schema-generator-cli.jar generate -i https://raw.githubusercontent.com/openapi-json-schema-tools/openapi-json-schema-generator/master/src/test/resources/3_0/petstore.yaml -g python -o c:\temp\python_api_client)

To get a list of general options available, please run java -jar target/openapi-json-schema-generator-cli.jar help generate

To get a list of python specified options (which can be passed to the generator with a config file via the -c option), please run java -jar target/openapi-json-schema-generator-cli.jar config-help -g python

Usage

To generate a sample client library

You can build a client against the Petstore API as follows:

./bin/generate-samples.sh ./bin/generate_samples_configs/python.yaml

(On Windows, please install GIT Bash for Windows to run the command above)

This script will run the generator with this command:

java -jar target/openapi-json-schema-generator-cli.jar generate \
  -i https://raw.githubusercontent.com/openapijsonschematools/openapi-json-schema-generator/master/src/test/resources/3_0/petstore.yaml \
  -g python \
  -t src/main/resources/python \
  --additional-properties packageName=petstore_api \
  -o samples/client/petstore/python

with a number of options. The python options are documented here.

You can also get the options with the help generate command (below only shows partial results):

NAME
        openapi-json-schema-generator-cli generate - Generate code with the specified
        generator.

SYNOPSIS
        openapi-json-schema-generator-cli generate
                [(-a <authorization> | --auth <authorization>)]
                [--api-name-suffix <api name suffix>] [--api-package <api package>]
                [--artifact-id <artifact id>] [--artifact-version <artifact version>]
                [(-c <configuration file> | --config <configuration file>)] [--dry-run]
                [(-e <templating engine> | --engine <templating engine>)]
                [--enable-post-process-file]
                [(-g <generator name> | --generator-name <generator name>)]
                [--git-host <git host>] [--git-repo-id <git repo id>]
                [--git-user-id <git user id>] [--global-property <global properties>...]
                [--group-id <group id>] [--hide-generation-timestamp]
                [--http-user-agent <http user agent>]
                [(-i <spec file> | --input-spec <spec file>)]
                [--ignore-file-override <ignore file override location>]
                [--ints-allowed-for-float-double-formats]
                [--invoker-package <invoker package>] [--minimal-update]
                [--model-name-prefix <model name prefix>]
                [--model-name-suffix <model name suffix>]
                [(-o <output directory> | --output <output directory>)] [(-p <additional properties> | --additional-properties <additional properties>)...]
                [--package-name <package name>] [--release-note <release note>]
                [--remove-enum-value-prefix] [--remove-operation-id-prefix]
                [(-s | --skip-overwrite)] [--skip-operation-example]
                [--skip-validate-spec] [--strict-spec <true/false strict behavior>]
                [(-t <template directory> | --template-dir <template directory>)]
                [(-v | --verbose)]
generate OPTIONS ```text OPTIONS -a , --auth adds authorization headers when fetching the OpenAPI definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values --api-name-suffix Suffix that will be appended to all API names ('tags'). Default: Api. e.g. Pet => PetApi. Note: Only ruby, python, jaxrs generators support this feature at the moment. --api-package package for generated api classes --artifact-id artifactId in generated pom.xml. This also becomes part of the generated library's filename --artifact-version artifact version in generated pom.xml. This also becomes part of the generated library's filename -c , --config Path to configuration file. It can be JSON or YAML. If file is JSON, the content should have the format {"optionKey":"optionValue", "optionKey1":"optionValue1"...}. If file is YAML, the content should have the format optionKey: optionValue. Supported options can be different for each language. Run config-help -g {generator name} command for language-specific config options. --dry-run Try things out and report on potential changes (without actually making changes). -e , --engine templating engine: "handlebars"(default) or "mustache" --enable-post-process-file Enable post-processing file using environment variables. -g , --generator-name generator to use (see list command for list) --git-host Git host, e.g. gitlab.com. --git-repo-id Git repo ID, e.g. openapi-generator. --git-user-id Git user ID, e.g. openapijsonschematools. --global-property sets specified global properties (previously called 'system properties') in the format of name=value,name=value (or multiple options, each with name=value) --group-id groupId in generated pom.xml --hide-generation-timestamp Hides the generation timestamp when files are generated. --http-user-agent HTTP user agent, e.g. codegen_csharp_api_client, default to 'OpenAPI-Generator/{packageVersion}/{language}' -i , --input-spec location of the OpenAPI spec, as URL or file (required if not loaded via config using -c) --ignore-file-override Specifies an override location for the .openapi-generator-ignore file. Most useful on initial generation. --ints-allowed-for-float-double-formats Integers are allowed in for type: number format:float/double payloads --invoker-package root package for generated code --minimal-update Only write output files that have changed. --model-name-prefix Prefix that will be prepended to all model names. --model-name-suffix Suffix that will be appended to all model names. -o , --output where to write the generated files (current dir by default) -p , --additional-properties sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value. You can also have multiple occurrences of this option. --package-name package for generated classes (where supported) --release-note Release note, default to 'Minor update'. --remove-enum-value-prefix Remove the common prefix of enum values --remove-operation-id-prefix Remove prefix of operationId, e.g. config_getId => getId -s, --skip-overwrite specifies if the existing files should be overwritten during the generation. --skip-operation-example Skip examples defined in operations to avoid out of memory errors. --skip-validate-spec Skips the default behavior of validating an input specification. --strict-spec 'MUST' and 'SHALL' wording in OpenAPI spec is strictly adhered to. e.g. when false, no fixes will be applied to documents which pass validation but don't follow the spec. -t